@blockcast/mmt-container 0.1.0 → 0.3.0-main.288475b64b3e

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 (800) hide show
  1. package/README.md +538 -0
  2. package/dist/.build-stamp +0 -0
  3. package/dist/__tests__/test-utils.d.ts +71 -0
  4. package/dist/__tests__/test-utils.d.ts.map +1 -0
  5. package/dist/align.d.ts +152 -0
  6. package/dist/align.d.ts.map +1 -0
  7. package/dist/align.js +88 -0
  8. package/dist/align.js.map +7 -0
  9. package/dist/audio-init-parser.d.ts +66 -0
  10. package/dist/audio-init-parser.d.ts.map +1 -0
  11. package/dist/audio-init-parser.js +118 -0
  12. package/dist/audio-init-parser.js.map +7 -0
  13. package/dist/audio-ring-buffer.d.ts +50 -0
  14. package/dist/audio-ring-buffer.d.ts.map +1 -0
  15. package/dist/audio-ring-buffer.js +80 -0
  16. package/dist/audio-ring-buffer.js.map +7 -0
  17. package/dist/authored-timing.d.ts +32 -0
  18. package/dist/authored-timing.d.ts.map +1 -0
  19. package/dist/authored-timing.js +32 -0
  20. package/dist/authored-timing.js.map +7 -0
  21. package/dist/block-policy.d.ts +314 -0
  22. package/dist/block-policy.d.ts.map +1 -0
  23. package/dist/block-policy.js +466 -0
  24. package/dist/block-policy.js.map +7 -0
  25. package/dist/browser-runtime.js +26457 -0
  26. package/dist/browser-runtime.js.map +7 -0
  27. package/dist/carp-catalog.d.ts +445 -0
  28. package/dist/carp-catalog.d.ts.map +1 -0
  29. package/dist/carp-catalog.js +998 -0
  30. package/dist/carp-catalog.js.map +7 -0
  31. package/dist/catalog-fec-params.d.ts +315 -0
  32. package/dist/catalog-fec-params.d.ts.map +1 -0
  33. package/dist/catalog-fec-params.js +730 -0
  34. package/dist/catalog-fec-params.js.map +7 -0
  35. package/dist/catalog-network-source.d.ts +42 -0
  36. package/dist/catalog-network-source.d.ts.map +1 -0
  37. package/dist/catalog-network-source.js +46 -0
  38. package/dist/catalog-network-source.js.map +7 -0
  39. package/dist/catalog-validator.d.ts +18 -0
  40. package/dist/catalog-validator.d.ts.map +1 -0
  41. package/dist/catalog-validator.js +7747 -0
  42. package/dist/catalog-validator.js.map +7 -0
  43. package/dist/cmaf-block-assembler.d.ts +285 -0
  44. package/dist/cmaf-block-assembler.d.ts.map +1 -0
  45. package/dist/cmaf-block-assembler.js +1966 -0
  46. package/dist/cmaf-block-assembler.js.map +7 -0
  47. package/dist/cmaf-group-batcher.d.ts +38 -0
  48. package/dist/cmaf-group-batcher.d.ts.map +1 -0
  49. package/dist/cmaf-group-batcher.js +176 -0
  50. package/dist/cmaf-group-batcher.js.map +7 -0
  51. package/dist/cmcd-producer.d.ts +104 -0
  52. package/dist/cmcd-producer.d.ts.map +1 -0
  53. package/dist/cmcd-producer.js +183 -0
  54. package/dist/cmcd-producer.js.map +7 -0
  55. package/dist/codec-utils.d.ts +384 -0
  56. package/dist/codec-utils.d.ts.map +1 -0
  57. package/dist/codec-utils.js +1546 -0
  58. package/dist/codec-utils.js.map +7 -0
  59. package/dist/conceal-timeline.d.ts +146 -0
  60. package/dist/conceal-timeline.d.ts.map +1 -0
  61. package/dist/conceal-timeline.js +137 -0
  62. package/dist/conceal-timeline.js.map +7 -0
  63. package/dist/delivery-gap.d.ts +75 -0
  64. package/dist/delivery-gap.d.ts.map +1 -0
  65. package/dist/delivery-gap.js +88 -0
  66. package/dist/delivery-gap.js.map +7 -0
  67. package/dist/duplicate-ledger.d.ts +197 -0
  68. package/dist/duplicate-ledger.d.ts.map +1 -0
  69. package/dist/duplicate-ledger.js +226 -0
  70. package/dist/duplicate-ledger.js.map +7 -0
  71. package/dist/fec-codec.d.ts +32 -0
  72. package/dist/fec-codec.d.ts.map +1 -0
  73. package/dist/fec-codec.js +47 -0
  74. package/dist/fec-codec.js.map +7 -0
  75. package/dist/fec-manager.d.ts +589 -0
  76. package/dist/fec-manager.d.ts.map +1 -0
  77. package/dist/fec-manager.js +3840 -0
  78. package/dist/fec-manager.js.map +7 -0
  79. package/dist/fec-starvation-detector.d.ts +59 -0
  80. package/dist/fec-starvation-detector.d.ts.map +1 -0
  81. package/dist/fec-starvation-detector.js +60 -0
  82. package/dist/fec-starvation-detector.js.map +7 -0
  83. package/dist/fec-state.d.ts +140 -0
  84. package/dist/fec-state.d.ts.map +1 -0
  85. package/dist/fec-state.js +86 -0
  86. package/dist/fec-state.js.map +7 -0
  87. package/dist/fec-worker-setup.d.ts +100 -0
  88. package/dist/fec-worker-setup.d.ts.map +1 -0
  89. package/dist/fec-worker-setup.js +671 -0
  90. package/dist/fec-worker-setup.js.map +7 -0
  91. package/dist/fmp4-completion.d.ts +30 -0
  92. package/dist/fmp4-completion.d.ts.map +1 -0
  93. package/dist/fmp4-completion.js +21 -0
  94. package/dist/fmp4-completion.js.map +7 -0
  95. package/dist/fmp4-reader.d.ts +37 -0
  96. package/dist/fmp4-reader.d.ts.map +1 -0
  97. package/dist/fmp4-reader.js +100 -0
  98. package/dist/fmp4-reader.js.map +7 -0
  99. package/dist/index.d.ts +44 -3
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +464 -14
  102. package/dist/index.js.map +7 -1
  103. package/dist/iso-block-locator.d.ts +118 -0
  104. package/dist/iso-block-locator.d.ts.map +1 -0
  105. package/dist/iso-block-locator.js +288 -0
  106. package/dist/iso-block-locator.js.map +7 -0
  107. package/dist/iso-bmff-timing.d.ts +78 -0
  108. package/dist/iso-bmff-timing.d.ts.map +1 -0
  109. package/dist/iso-bmff-timing.js +593 -0
  110. package/dist/iso-bmff-timing.js.map +7 -0
  111. package/dist/loc.d.ts +70 -75
  112. package/dist/loc.d.ts.map +1 -1
  113. package/dist/loc.js +106 -192
  114. package/dist/loc.js.map +7 -1
  115. package/dist/manifest-auth-plan.d.ts +30 -0
  116. package/dist/manifest-auth-plan.d.ts.map +1 -0
  117. package/dist/manifest-auth-plan.js +1266 -0
  118. package/dist/manifest-auth-plan.js.map +7 -0
  119. package/dist/media-router.d.ts +262 -0
  120. package/dist/media-router.d.ts.map +1 -0
  121. package/dist/media-router.js +584 -0
  122. package/dist/media-router.js.map +7 -0
  123. package/dist/mfu-reassembler.d.ts +313 -9
  124. package/dist/mfu-reassembler.d.ts.map +1 -1
  125. package/dist/mfu-reassembler.js +3050 -285
  126. package/dist/mfu-reassembler.js.map +7 -1
  127. package/dist/mfu-reassembly-policy.d.ts +24 -0
  128. package/dist/mfu-reassembly-policy.d.ts.map +1 -0
  129. package/dist/mfu-reassembly-policy.js +99 -0
  130. package/dist/mfu-reassembly-policy.js.map +7 -0
  131. package/dist/mmtp-container-parser.d.ts +573 -0
  132. package/dist/mmtp-container-parser.d.ts.map +1 -0
  133. package/dist/mmtp-container-parser.js +6601 -0
  134. package/dist/mmtp-container-parser.js.map +7 -0
  135. package/dist/mmtp-container-parser.no-modules.js +9645 -0
  136. package/dist/mmtp-container-parser.no-modules.js.map +7 -0
  137. package/dist/mmtp-decode-pipeline.d.ts +138 -0
  138. package/dist/mmtp-decode-pipeline.d.ts.map +1 -0
  139. package/dist/mmtp-decode-pipeline.js +6835 -0
  140. package/dist/mmtp-decode-pipeline.js.map +7 -0
  141. package/dist/mmtp-router.d.ts +702 -0
  142. package/dist/mmtp-router.d.ts.map +1 -0
  143. package/dist/mmtp-router.js +11193 -0
  144. package/dist/mmtp-router.js.map +7 -0
  145. package/dist/mmtp-to-cmaf.d.ts +187 -0
  146. package/dist/mmtp-to-cmaf.d.ts.map +1 -0
  147. package/dist/mmtp-to-cmaf.js +716 -0
  148. package/dist/mmtp-to-cmaf.js.map +7 -0
  149. package/dist/multicast-auth-catalog.d.ts +115 -0
  150. package/dist/multicast-auth-catalog.d.ts.map +1 -0
  151. package/dist/multicast-auth-catalog.js +202 -0
  152. package/dist/multicast-auth-catalog.js.map +7 -0
  153. package/dist/multicast-input.d.ts +141 -0
  154. package/dist/multicast-input.d.ts.map +1 -0
  155. package/dist/multicast-input.js +389 -0
  156. package/dist/multicast-input.js.map +7 -0
  157. package/dist/multicast-manager.d.ts +699 -0
  158. package/dist/multicast-manager.d.ts.map +1 -0
  159. package/dist/multicast-manager.js +19120 -0
  160. package/dist/multicast-manager.js.map +7 -0
  161. package/dist/multicast-transport.d.ts +271 -0
  162. package/dist/multicast-transport.d.ts.map +1 -0
  163. package/dist/multicast-transport.js +2262 -0
  164. package/dist/multicast-transport.js.map +7 -0
  165. package/dist/multicast-unwrap.d.ts +57 -0
  166. package/dist/multicast-unwrap.d.ts.map +1 -0
  167. package/dist/multicast-unwrap.js +417 -0
  168. package/dist/multicast-unwrap.js.map +7 -0
  169. package/dist/no-modules.d.ts +10 -0
  170. package/dist/no-modules.d.ts.map +1 -0
  171. package/dist/no-modules.js +9520 -0
  172. package/dist/no-modules.js.map +7 -0
  173. package/dist/phase14-catalog-override.d.ts +126 -0
  174. package/dist/phase14-catalog-override.d.ts.map +1 -0
  175. package/dist/phase14-catalog-override.js +155 -0
  176. package/dist/phase14-catalog-override.js.map +7 -0
  177. package/dist/repair-fetch.d.ts +281 -0
  178. package/dist/repair-fetch.d.ts.map +1 -0
  179. package/dist/repair-fetch.js +391 -0
  180. package/dist/repair-fetch.js.map +7 -0
  181. package/dist/repair-layers.d.ts +169 -0
  182. package/dist/repair-layers.d.ts.map +1 -0
  183. package/dist/repair-layers.js +351 -0
  184. package/dist/repair-layers.js.map +7 -0
  185. package/dist/sample-combiner.d.ts +212 -0
  186. package/dist/sample-combiner.d.ts.map +1 -0
  187. package/dist/sample-combiner.js +595 -0
  188. package/dist/sample-combiner.js.map +7 -0
  189. package/dist/signaling.d.ts +29 -0
  190. package/dist/signaling.d.ts.map +1 -0
  191. package/dist/signaling.js +568 -0
  192. package/dist/signaling.js.map +7 -0
  193. package/dist/source-auth.d.ts +2 -0
  194. package/dist/source-auth.d.ts.map +1 -0
  195. package/dist/source-auth.js +1209 -0
  196. package/dist/source-auth.js.map +7 -0
  197. package/dist/switching-set-alignment.d.ts +61 -0
  198. package/dist/switching-set-alignment.d.ts.map +1 -0
  199. package/dist/switching-set-alignment.js +70 -0
  200. package/dist/switching-set-alignment.js.map +7 -0
  201. package/dist/timestamp-codec.d.ts +34 -0
  202. package/dist/timestamp-codec.d.ts.map +1 -0
  203. package/dist/timestamp-codec.js +472 -0
  204. package/dist/timestamp-codec.js.map +7 -0
  205. package/dist/track-pipeline-setup.d.ts +83 -0
  206. package/dist/track-pipeline-setup.d.ts.map +1 -0
  207. package/dist/track-pipeline-setup.js +291 -0
  208. package/dist/track-pipeline-setup.js.map +7 -0
  209. package/dist/track-pipeline.d.ts +121 -0
  210. package/dist/track-pipeline.d.ts.map +1 -0
  211. package/dist/track-pipeline.js +209 -0
  212. package/dist/track-pipeline.js.map +7 -0
  213. package/dist/track-session.d.ts +414 -0
  214. package/dist/track-session.d.ts.map +1 -0
  215. package/dist/track-session.js +754 -0
  216. package/dist/track-session.js.map +7 -0
  217. package/dist/transport-pool.d.ts +69 -0
  218. package/dist/transport-pool.d.ts.map +1 -0
  219. package/dist/transport-pool.js +74 -0
  220. package/dist/transport-pool.js.map +7 -0
  221. package/dist/wasm-mfu-reassembler.d.ts +97 -0
  222. package/dist/wasm-mfu-reassembler.d.ts.map +1 -0
  223. package/dist/wasm-mfu-reassembler.js +2132 -0
  224. package/dist/wasm-mfu-reassembler.js.map +7 -0
  225. package/dist/wasm-mmtp-container-parser.d.ts +10 -0
  226. package/dist/wasm-mmtp-container-parser.d.ts.map +1 -0
  227. package/dist/wasm-mmtp-container-parser.js +6855 -0
  228. package/dist/wasm-mmtp-container-parser.js.map +7 -0
  229. package/node_modules/@blockcast/fec-worker/README.md +223 -0
  230. package/node_modules/@blockcast/fec-worker/dist/.build-stamp +0 -0
  231. package/node_modules/@blockcast/fec-worker/dist/block-order.d.ts +22 -0
  232. package/node_modules/@blockcast/fec-worker/dist/block-order.d.ts.map +1 -0
  233. package/node_modules/@blockcast/fec-worker/dist/block-order.js +48 -0
  234. package/node_modules/@blockcast/fec-worker/dist/block-order.js.map +1 -0
  235. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +92 -0
  236. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -0
  237. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +345 -0
  238. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -0
  239. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +373 -0
  240. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -0
  241. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.js +11 -0
  242. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.js.map +1 -0
  243. package/node_modules/@blockcast/fec-worker/dist/fec-worker.d.ts +14 -0
  244. package/node_modules/@blockcast/fec-worker/dist/fec-worker.d.ts.map +1 -0
  245. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +764 -0
  246. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +7 -0
  247. package/node_modules/@blockcast/fec-worker/dist/index.d.ts +10 -0
  248. package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -0
  249. package/node_modules/@blockcast/fec-worker/dist/index.js +8 -0
  250. package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -0
  251. package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.d.ts +20 -0
  252. package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.d.ts.map +1 -0
  253. package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.js +370 -0
  254. package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.js.map +7 -0
  255. package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.d.ts +104 -0
  256. package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.d.ts.map +1 -0
  257. package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.js +181 -0
  258. package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.js.map +1 -0
  259. package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.d.ts +194 -0
  260. package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.d.ts.map +1 -0
  261. package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.js +62 -0
  262. package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.js.map +1 -0
  263. package/node_modules/@blockcast/fec-worker/dist/transfer.d.ts +9 -0
  264. package/node_modules/@blockcast/fec-worker/dist/transfer.d.ts.map +1 -0
  265. package/node_modules/@blockcast/fec-worker/dist/transfer.js +13 -0
  266. package/node_modules/@blockcast/fec-worker/dist/transfer.js.map +1 -0
  267. package/node_modules/@blockcast/fec-worker/package.json +59 -0
  268. package/node_modules/@blockcast/fec-worker/src/block-order.ts +59 -0
  269. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +391 -0
  270. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +392 -0
  271. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +1386 -0
  272. package/node_modules/@blockcast/fec-worker/src/index.ts +35 -0
  273. package/node_modules/@blockcast/fec-worker/src/shred-fec-worker.ts +589 -0
  274. package/node_modules/@blockcast/fec-worker/src/shred-worker-client.ts +222 -0
  275. package/node_modules/@blockcast/fec-worker/src/shred-worker-types.ts +209 -0
  276. package/node_modules/@blockcast/fec-worker/src/transfer.ts +12 -0
  277. package/node_modules/@blockcast/mmt-alta-parse/README.md +181 -0
  278. package/node_modules/@blockcast/mmt-alta-parse/dist/.build-stamp +0 -0
  279. package/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts +57 -0
  280. package/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts.map +1 -0
  281. package/node_modules/@blockcast/mmt-alta-parse/dist/index.js +115 -0
  282. package/node_modules/@blockcast/mmt-alta-parse/dist/index.js.map +1 -0
  283. package/node_modules/@blockcast/mmt-alta-parse/package.json +50 -0
  284. package/node_modules/@blockcast/mmt-alta-parse/src/index.ts +136 -0
  285. package/node_modules/@blockcast/mmt-base/README.md +134 -0
  286. package/node_modules/@blockcast/mmt-base/dist/.build-stamp +0 -0
  287. package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts +55 -0
  288. package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts.map +1 -0
  289. package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js +132 -0
  290. package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js.map +1 -0
  291. package/node_modules/@blockcast/mmt-base/dist/index.d.ts +7 -0
  292. package/node_modules/@blockcast/mmt-base/dist/index.d.ts.map +1 -0
  293. package/node_modules/@blockcast/mmt-base/dist/index.js +7 -0
  294. package/node_modules/@blockcast/mmt-base/dist/index.js.map +1 -0
  295. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +292 -0
  296. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -0
  297. package/node_modules/@blockcast/mmt-base/dist/mmtp.js +612 -0
  298. package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -0
  299. package/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts +18 -0
  300. package/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts.map +1 -0
  301. package/node_modules/@blockcast/mmt-base/dist/net-constants.js +18 -0
  302. package/node_modules/@blockcast/mmt-base/dist/net-constants.js.map +1 -0
  303. package/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts +47 -0
  304. package/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts.map +1 -0
  305. package/node_modules/@blockcast/mmt-base/dist/ntp-short.js +54 -0
  306. package/node_modules/@blockcast/mmt-base/dist/ntp-short.js.map +1 -0
  307. package/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts +28 -0
  308. package/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts.map +1 -0
  309. package/node_modules/@blockcast/mmt-base/dist/serial-number.js +44 -0
  310. package/node_modules/@blockcast/mmt-base/dist/serial-number.js.map +1 -0
  311. package/node_modules/@blockcast/mmt-base/dist/signalling.d.ts +314 -0
  312. package/node_modules/@blockcast/mmt-base/dist/signalling.d.ts.map +1 -0
  313. package/node_modules/@blockcast/mmt-base/dist/signalling.js +637 -0
  314. package/node_modules/@blockcast/mmt-base/dist/signalling.js.map +1 -0
  315. package/node_modules/@blockcast/mmt-base/package.json +49 -0
  316. package/node_modules/@blockcast/mmt-base/src/fec-block-profile.ts +145 -0
  317. package/node_modules/@blockcast/mmt-base/src/index.ts +6 -0
  318. package/node_modules/@blockcast/mmt-base/src/mmtp.ts +892 -0
  319. package/node_modules/@blockcast/mmt-base/src/net-constants.ts +17 -0
  320. package/node_modules/@blockcast/mmt-base/src/ntp-short.ts +67 -0
  321. package/node_modules/@blockcast/mmt-base/src/serial-number.ts +49 -0
  322. package/node_modules/@blockcast/mmt-base/src/signalling.ts +860 -0
  323. package/node_modules/@blockcast/mmt-fec/README.md +271 -0
  324. package/node_modules/@blockcast/mmt-fec/dist/.build-stamp +0 -0
  325. package/node_modules/@blockcast/mmt-fec/dist/block-manager.d.ts +82 -0
  326. package/node_modules/@blockcast/mmt-fec/dist/block-manager.d.ts.map +1 -0
  327. package/node_modules/@blockcast/mmt-fec/dist/block-manager.js +296 -0
  328. package/node_modules/@blockcast/mmt-fec/dist/block-manager.js.map +1 -0
  329. package/node_modules/@blockcast/mmt-fec/dist/block-processor.d.ts +105 -0
  330. package/node_modules/@blockcast/mmt-fec/dist/block-processor.d.ts.map +1 -0
  331. package/node_modules/@blockcast/mmt-fec/dist/block-processor.js +222 -0
  332. package/node_modules/@blockcast/mmt-fec/dist/block-processor.js.map +1 -0
  333. package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.d.ts +46 -0
  334. package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.d.ts.map +1 -0
  335. package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.js +96 -0
  336. package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.js.map +1 -0
  337. package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.d.ts +33 -0
  338. package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.d.ts.map +1 -0
  339. package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.js +57 -0
  340. package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.js.map +1 -0
  341. package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.d.ts +149 -0
  342. package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.d.ts.map +1 -0
  343. package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.js +161 -0
  344. package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.js.map +1 -0
  345. package/node_modules/@blockcast/mmt-fec/dist/index.d.ts +28 -0
  346. package/node_modules/@blockcast/mmt-fec/dist/index.d.ts.map +1 -0
  347. package/node_modules/@blockcast/mmt-fec/dist/index.js +28 -0
  348. package/node_modules/@blockcast/mmt-fec/dist/index.js.map +1 -0
  349. package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.d.ts +20 -0
  350. package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.d.ts.map +1 -0
  351. package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.js +28 -0
  352. package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.js.map +1 -0
  353. package/node_modules/@blockcast/mmt-fec/dist/oti.d.ts +258 -0
  354. package/node_modules/@blockcast/mmt-fec/dist/oti.d.ts.map +1 -0
  355. package/node_modules/@blockcast/mmt-fec/dist/oti.js +382 -0
  356. package/node_modules/@blockcast/mmt-fec/dist/oti.js.map +1 -0
  357. package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.d.ts +41 -0
  358. package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.d.ts.map +1 -0
  359. package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.js +81 -0
  360. package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.js.map +1 -0
  361. package/node_modules/@blockcast/mmt-fec/dist/repair-group.d.ts +82 -0
  362. package/node_modules/@blockcast/mmt-fec/dist/repair-group.d.ts.map +1 -0
  363. package/node_modules/@blockcast/mmt-fec/dist/repair-group.js +170 -0
  364. package/node_modules/@blockcast/mmt-fec/dist/repair-group.js.map +1 -0
  365. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/README.md +181 -0
  366. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/.build-stamp +0 -0
  367. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts +57 -0
  368. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts.map +1 -0
  369. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.js +115 -0
  370. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.js.map +1 -0
  371. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/package.json +50 -0
  372. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/src/index.ts +136 -0
  373. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +134 -0
  374. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/.build-stamp +0 -0
  375. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts +55 -0
  376. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts.map +1 -0
  377. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js +132 -0
  378. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js.map +1 -0
  379. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.d.ts +7 -0
  380. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.d.ts.map +1 -0
  381. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.js +7 -0
  382. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.js.map +1 -0
  383. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +292 -0
  384. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -0
  385. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +612 -0
  386. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -0
  387. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts +18 -0
  388. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts.map +1 -0
  389. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.js +18 -0
  390. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.js.map +1 -0
  391. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts +47 -0
  392. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts.map +1 -0
  393. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.js +54 -0
  394. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.js.map +1 -0
  395. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts +28 -0
  396. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts.map +1 -0
  397. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.js +44 -0
  398. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.js.map +1 -0
  399. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.d.ts +314 -0
  400. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.d.ts.map +1 -0
  401. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.js +637 -0
  402. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.js.map +1 -0
  403. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/package.json +49 -0
  404. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/fec-block-profile.ts +145 -0
  405. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/index.ts +6 -0
  406. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +892 -0
  407. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/net-constants.ts +17 -0
  408. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/ntp-short.ts +67 -0
  409. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/serial-number.ts +49 -0
  410. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/signalling.ts +860 -0
  411. package/node_modules/@blockcast/mmt-fec/package.json +79 -0
  412. package/node_modules/@blockcast/mmt-fec/src/block-manager.ts +371 -0
  413. package/node_modules/@blockcast/mmt-fec/src/block-processor.ts +360 -0
  414. package/node_modules/@blockcast/mmt-fec/src/cmaf-recovery.ts +127 -0
  415. package/node_modules/@blockcast/mmt-fec/src/cmaf-symbols.ts +68 -0
  416. package/node_modules/@blockcast/mmt-fec/src/fec-block-mapper.ts +225 -0
  417. package/node_modules/@blockcast/mmt-fec/src/index.ts +93 -0
  418. package/node_modules/@blockcast/mmt-fec/src/loc-symbols.ts +34 -0
  419. package/node_modules/@blockcast/mmt-fec/src/oti.ts +463 -0
  420. package/node_modules/@blockcast/mmt-fec/src/reorder-buffer.ts +101 -0
  421. package/node_modules/@blockcast/mmt-fec/src/repair-group.ts +195 -0
  422. package/node_modules/@blockcast/mmt-manifest-verify/dist/.build-stamp +0 -0
  423. package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.d.ts +28 -0
  424. package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.d.ts.map +1 -0
  425. package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.js +128 -0
  426. package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.js.map +1 -0
  427. package/node_modules/@blockcast/mmt-manifest-verify/dist/index.d.ts +4 -0
  428. package/node_modules/@blockcast/mmt-manifest-verify/dist/index.d.ts.map +1 -0
  429. package/node_modules/@blockcast/mmt-manifest-verify/dist/index.js +4 -0
  430. package/node_modules/@blockcast/mmt-manifest-verify/dist/index.js.map +1 -0
  431. package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.d.ts +37 -0
  432. package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.d.ts.map +1 -0
  433. package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.js +179 -0
  434. package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.js.map +1 -0
  435. package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.d.ts +99 -0
  436. package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.d.ts.map +1 -0
  437. package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.js +492 -0
  438. package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.js.map +1 -0
  439. package/node_modules/@blockcast/mmt-manifest-verify/package.json +45 -0
  440. package/node_modules/@blockcast/mmt-manifest-verify/src/admission.ts +171 -0
  441. package/node_modules/@blockcast/mmt-manifest-verify/src/index.ts +3 -0
  442. package/node_modules/@blockcast/mmt-manifest-verify/src/source-auth.ts +230 -0
  443. package/node_modules/@blockcast/mmt-manifest-verify/src/verifier.ts +669 -0
  444. package/node_modules/@noble/hashes/LICENSE +21 -0
  445. package/node_modules/@noble/hashes/README.md +521 -0
  446. package/node_modules/@noble/hashes/_assert.d.ts +17 -0
  447. package/node_modules/@noble/hashes/_assert.d.ts.map +1 -0
  448. package/node_modules/@noble/hashes/_assert.js +18 -0
  449. package/node_modules/@noble/hashes/_assert.js.map +1 -0
  450. package/node_modules/@noble/hashes/_blake.d.ts +14 -0
  451. package/node_modules/@noble/hashes/_blake.d.ts.map +1 -0
  452. package/node_modules/@noble/hashes/_blake.js +50 -0
  453. package/node_modules/@noble/hashes/_blake.js.map +1 -0
  454. package/node_modules/@noble/hashes/_md.d.ts +51 -0
  455. package/node_modules/@noble/hashes/_md.d.ts.map +1 -0
  456. package/node_modules/@noble/hashes/_md.js +162 -0
  457. package/node_modules/@noble/hashes/_md.js.map +1 -0
  458. package/node_modules/@noble/hashes/_u64.d.ts +55 -0
  459. package/node_modules/@noble/hashes/_u64.d.ts.map +1 -0
  460. package/node_modules/@noble/hashes/_u64.js +90 -0
  461. package/node_modules/@noble/hashes/_u64.js.map +1 -0
  462. package/node_modules/@noble/hashes/argon2.d.ts +32 -0
  463. package/node_modules/@noble/hashes/argon2.d.ts.map +1 -0
  464. package/node_modules/@noble/hashes/argon2.js +401 -0
  465. package/node_modules/@noble/hashes/argon2.js.map +1 -0
  466. package/node_modules/@noble/hashes/blake1.d.ts +106 -0
  467. package/node_modules/@noble/hashes/blake1.d.ts.map +1 -0
  468. package/node_modules/@noble/hashes/blake1.js +459 -0
  469. package/node_modules/@noble/hashes/blake1.js.map +1 -0
  470. package/node_modules/@noble/hashes/blake2.d.ts +116 -0
  471. package/node_modules/@noble/hashes/blake2.d.ts.map +1 -0
  472. package/node_modules/@noble/hashes/blake2.js +420 -0
  473. package/node_modules/@noble/hashes/blake2.js.map +1 -0
  474. package/node_modules/@noble/hashes/blake2b.d.ts +11 -0
  475. package/node_modules/@noble/hashes/blake2b.d.ts.map +1 -0
  476. package/node_modules/@noble/hashes/blake2b.js +14 -0
  477. package/node_modules/@noble/hashes/blake2b.js.map +1 -0
  478. package/node_modules/@noble/hashes/blake2s.d.ts +20 -0
  479. package/node_modules/@noble/hashes/blake2s.d.ts.map +1 -0
  480. package/node_modules/@noble/hashes/blake2s.js +24 -0
  481. package/node_modules/@noble/hashes/blake2s.js.map +1 -0
  482. package/node_modules/@noble/hashes/blake3.d.ts +54 -0
  483. package/node_modules/@noble/hashes/blake3.d.ts.map +1 -0
  484. package/node_modules/@noble/hashes/blake3.js +255 -0
  485. package/node_modules/@noble/hashes/blake3.js.map +1 -0
  486. package/node_modules/@noble/hashes/crypto.d.ts +2 -0
  487. package/node_modules/@noble/hashes/crypto.d.ts.map +1 -0
  488. package/node_modules/@noble/hashes/crypto.js +5 -0
  489. package/node_modules/@noble/hashes/crypto.js.map +1 -0
  490. package/node_modules/@noble/hashes/cryptoNode.d.ts +2 -0
  491. package/node_modules/@noble/hashes/cryptoNode.d.ts.map +1 -0
  492. package/node_modules/@noble/hashes/cryptoNode.js +18 -0
  493. package/node_modules/@noble/hashes/cryptoNode.js.map +1 -0
  494. package/node_modules/@noble/hashes/eskdf.d.ts +47 -0
  495. package/node_modules/@noble/hashes/eskdf.d.ts.map +1 -0
  496. package/node_modules/@noble/hashes/eskdf.js +166 -0
  497. package/node_modules/@noble/hashes/eskdf.js.map +1 -0
  498. package/node_modules/@noble/hashes/esm/_assert.d.ts +17 -0
  499. package/node_modules/@noble/hashes/esm/_assert.d.ts.map +1 -0
  500. package/node_modules/@noble/hashes/esm/_assert.js +15 -0
  501. package/node_modules/@noble/hashes/esm/_assert.js.map +1 -0
  502. package/node_modules/@noble/hashes/esm/_blake.d.ts +14 -0
  503. package/node_modules/@noble/hashes/esm/_blake.d.ts.map +1 -0
  504. package/node_modules/@noble/hashes/esm/_blake.js +45 -0
  505. package/node_modules/@noble/hashes/esm/_blake.js.map +1 -0
  506. package/node_modules/@noble/hashes/esm/_md.d.ts +51 -0
  507. package/node_modules/@noble/hashes/esm/_md.d.ts.map +1 -0
  508. package/node_modules/@noble/hashes/esm/_md.js +155 -0
  509. package/node_modules/@noble/hashes/esm/_md.js.map +1 -0
  510. package/node_modules/@noble/hashes/esm/_u64.d.ts +55 -0
  511. package/node_modules/@noble/hashes/esm/_u64.d.ts.map +1 -0
  512. package/node_modules/@noble/hashes/esm/_u64.js +67 -0
  513. package/node_modules/@noble/hashes/esm/_u64.js.map +1 -0
  514. package/node_modules/@noble/hashes/esm/argon2.d.ts +32 -0
  515. package/node_modules/@noble/hashes/esm/argon2.d.ts.map +1 -0
  516. package/node_modules/@noble/hashes/esm/argon2.js +392 -0
  517. package/node_modules/@noble/hashes/esm/argon2.js.map +1 -0
  518. package/node_modules/@noble/hashes/esm/blake1.d.ts +106 -0
  519. package/node_modules/@noble/hashes/esm/blake1.d.ts.map +1 -0
  520. package/node_modules/@noble/hashes/esm/blake1.js +452 -0
  521. package/node_modules/@noble/hashes/esm/blake1.js.map +1 -0
  522. package/node_modules/@noble/hashes/esm/blake2.d.ts +116 -0
  523. package/node_modules/@noble/hashes/esm/blake2.d.ts.map +1 -0
  524. package/node_modules/@noble/hashes/esm/blake2.js +413 -0
  525. package/node_modules/@noble/hashes/esm/blake2.js.map +1 -0
  526. package/node_modules/@noble/hashes/esm/blake2b.d.ts +11 -0
  527. package/node_modules/@noble/hashes/esm/blake2b.d.ts.map +1 -0
  528. package/node_modules/@noble/hashes/esm/blake2b.js +11 -0
  529. package/node_modules/@noble/hashes/esm/blake2b.js.map +1 -0
  530. package/node_modules/@noble/hashes/esm/blake2s.d.ts +20 -0
  531. package/node_modules/@noble/hashes/esm/blake2s.d.ts.map +1 -0
  532. package/node_modules/@noble/hashes/esm/blake2s.js +21 -0
  533. package/node_modules/@noble/hashes/esm/blake2s.js.map +1 -0
  534. package/node_modules/@noble/hashes/esm/blake3.d.ts +54 -0
  535. package/node_modules/@noble/hashes/esm/blake3.d.ts.map +1 -0
  536. package/node_modules/@noble/hashes/esm/blake3.js +251 -0
  537. package/node_modules/@noble/hashes/esm/blake3.js.map +1 -0
  538. package/node_modules/@noble/hashes/esm/crypto.d.ts +2 -0
  539. package/node_modules/@noble/hashes/esm/crypto.d.ts.map +1 -0
  540. package/node_modules/@noble/hashes/esm/crypto.js +2 -0
  541. package/node_modules/@noble/hashes/esm/crypto.js.map +1 -0
  542. package/node_modules/@noble/hashes/esm/cryptoNode.d.ts +2 -0
  543. package/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map +1 -0
  544. package/node_modules/@noble/hashes/esm/cryptoNode.js +15 -0
  545. package/node_modules/@noble/hashes/esm/cryptoNode.js.map +1 -0
  546. package/node_modules/@noble/hashes/esm/eskdf.d.ts +47 -0
  547. package/node_modules/@noble/hashes/esm/eskdf.d.ts.map +1 -0
  548. package/node_modules/@noble/hashes/esm/eskdf.js +160 -0
  549. package/node_modules/@noble/hashes/esm/eskdf.js.map +1 -0
  550. package/node_modules/@noble/hashes/esm/hkdf.d.ts +36 -0
  551. package/node_modules/@noble/hashes/esm/hkdf.d.ts.map +1 -0
  552. package/node_modules/@noble/hashes/esm/hkdf.js +82 -0
  553. package/node_modules/@noble/hashes/esm/hkdf.js.map +1 -0
  554. package/node_modules/@noble/hashes/esm/hmac.d.ts +35 -0
  555. package/node_modules/@noble/hashes/esm/hmac.d.ts.map +1 -0
  556. package/node_modules/@noble/hashes/esm/hmac.js +86 -0
  557. package/node_modules/@noble/hashes/esm/hmac.js.map +1 -0
  558. package/node_modules/@noble/hashes/esm/index.d.ts +2 -0
  559. package/node_modules/@noble/hashes/esm/index.d.ts.map +1 -0
  560. package/node_modules/@noble/hashes/esm/index.js +33 -0
  561. package/node_modules/@noble/hashes/esm/index.js.map +1 -0
  562. package/node_modules/@noble/hashes/esm/legacy.d.ts +71 -0
  563. package/node_modules/@noble/hashes/esm/legacy.d.ts.map +1 -0
  564. package/node_modules/@noble/hashes/esm/legacy.js +281 -0
  565. package/node_modules/@noble/hashes/esm/legacy.js.map +1 -0
  566. package/node_modules/@noble/hashes/esm/package.json +10 -0
  567. package/node_modules/@noble/hashes/esm/pbkdf2.d.ts +23 -0
  568. package/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map +1 -0
  569. package/node_modules/@noble/hashes/esm/pbkdf2.js +97 -0
  570. package/node_modules/@noble/hashes/esm/pbkdf2.js.map +1 -0
  571. package/node_modules/@noble/hashes/esm/ripemd160.d.ts +13 -0
  572. package/node_modules/@noble/hashes/esm/ripemd160.d.ts.map +1 -0
  573. package/node_modules/@noble/hashes/esm/ripemd160.js +13 -0
  574. package/node_modules/@noble/hashes/esm/ripemd160.js.map +1 -0
  575. package/node_modules/@noble/hashes/esm/scrypt.d.ts +34 -0
  576. package/node_modules/@noble/hashes/esm/scrypt.d.ts.map +1 -0
  577. package/node_modules/@noble/hashes/esm/scrypt.js +228 -0
  578. package/node_modules/@noble/hashes/esm/scrypt.js.map +1 -0
  579. package/node_modules/@noble/hashes/esm/sha1.d.ts +11 -0
  580. package/node_modules/@noble/hashes/esm/sha1.d.ts.map +1 -0
  581. package/node_modules/@noble/hashes/esm/sha1.js +11 -0
  582. package/node_modules/@noble/hashes/esm/sha1.js.map +1 -0
  583. package/node_modules/@noble/hashes/esm/sha2.d.ts +159 -0
  584. package/node_modules/@noble/hashes/esm/sha2.d.ts.map +1 -0
  585. package/node_modules/@noble/hashes/esm/sha2.js +375 -0
  586. package/node_modules/@noble/hashes/esm/sha2.js.map +1 -0
  587. package/node_modules/@noble/hashes/esm/sha256.d.ts +20 -0
  588. package/node_modules/@noble/hashes/esm/sha256.d.ts.map +1 -0
  589. package/node_modules/@noble/hashes/esm/sha256.js +20 -0
  590. package/node_modules/@noble/hashes/esm/sha256.js.map +1 -0
  591. package/node_modules/@noble/hashes/esm/sha3-addons.d.ts +142 -0
  592. package/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map +1 -0
  593. package/node_modules/@noble/hashes/esm/sha3-addons.js +393 -0
  594. package/node_modules/@noble/hashes/esm/sha3-addons.js.map +1 -0
  595. package/node_modules/@noble/hashes/esm/sha3.d.ts +53 -0
  596. package/node_modules/@noble/hashes/esm/sha3.d.ts.map +1 -0
  597. package/node_modules/@noble/hashes/esm/sha3.js +234 -0
  598. package/node_modules/@noble/hashes/esm/sha3.js.map +1 -0
  599. package/node_modules/@noble/hashes/esm/sha512.d.ts +26 -0
  600. package/node_modules/@noble/hashes/esm/sha512.d.ts.map +1 -0
  601. package/node_modules/@noble/hashes/esm/sha512.js +26 -0
  602. package/node_modules/@noble/hashes/esm/sha512.js.map +1 -0
  603. package/node_modules/@noble/hashes/esm/utils.d.ts +161 -0
  604. package/node_modules/@noble/hashes/esm/utils.d.ts.map +1 -0
  605. package/node_modules/@noble/hashes/esm/utils.js +281 -0
  606. package/node_modules/@noble/hashes/esm/utils.js.map +1 -0
  607. package/node_modules/@noble/hashes/hkdf.d.ts +36 -0
  608. package/node_modules/@noble/hashes/hkdf.d.ts.map +1 -0
  609. package/node_modules/@noble/hashes/hkdf.js +88 -0
  610. package/node_modules/@noble/hashes/hkdf.js.map +1 -0
  611. package/node_modules/@noble/hashes/hmac.d.ts +35 -0
  612. package/node_modules/@noble/hashes/hmac.d.ts.map +1 -0
  613. package/node_modules/@noble/hashes/hmac.js +91 -0
  614. package/node_modules/@noble/hashes/hmac.js.map +1 -0
  615. package/node_modules/@noble/hashes/index.d.ts +1 -0
  616. package/node_modules/@noble/hashes/index.d.ts.map +1 -0
  617. package/node_modules/@noble/hashes/index.js +33 -0
  618. package/node_modules/@noble/hashes/index.js.map +1 -0
  619. package/node_modules/@noble/hashes/legacy.d.ts +71 -0
  620. package/node_modules/@noble/hashes/legacy.d.ts.map +1 -0
  621. package/node_modules/@noble/hashes/legacy.js +287 -0
  622. package/node_modules/@noble/hashes/legacy.js.map +1 -0
  623. package/node_modules/@noble/hashes/package.json +266 -0
  624. package/node_modules/@noble/hashes/pbkdf2.d.ts +23 -0
  625. package/node_modules/@noble/hashes/pbkdf2.d.ts.map +1 -0
  626. package/node_modules/@noble/hashes/pbkdf2.js +101 -0
  627. package/node_modules/@noble/hashes/pbkdf2.js.map +1 -0
  628. package/node_modules/@noble/hashes/ripemd160.d.ts +13 -0
  629. package/node_modules/@noble/hashes/ripemd160.d.ts.map +1 -0
  630. package/node_modules/@noble/hashes/ripemd160.js +16 -0
  631. package/node_modules/@noble/hashes/ripemd160.js.map +1 -0
  632. package/node_modules/@noble/hashes/scrypt.d.ts +34 -0
  633. package/node_modules/@noble/hashes/scrypt.d.ts.map +1 -0
  634. package/node_modules/@noble/hashes/scrypt.js +232 -0
  635. package/node_modules/@noble/hashes/scrypt.js.map +1 -0
  636. package/node_modules/@noble/hashes/sha1.d.ts +11 -0
  637. package/node_modules/@noble/hashes/sha1.d.ts.map +1 -0
  638. package/node_modules/@noble/hashes/sha1.js +14 -0
  639. package/node_modules/@noble/hashes/sha1.js.map +1 -0
  640. package/node_modules/@noble/hashes/sha2.d.ts +159 -0
  641. package/node_modules/@noble/hashes/sha2.d.ts.map +1 -0
  642. package/node_modules/@noble/hashes/sha2.js +384 -0
  643. package/node_modules/@noble/hashes/sha2.js.map +1 -0
  644. package/node_modules/@noble/hashes/sha256.d.ts +20 -0
  645. package/node_modules/@noble/hashes/sha256.d.ts.map +1 -0
  646. package/node_modules/@noble/hashes/sha256.js +23 -0
  647. package/node_modules/@noble/hashes/sha256.js.map +1 -0
  648. package/node_modules/@noble/hashes/sha3-addons.d.ts +142 -0
  649. package/node_modules/@noble/hashes/sha3-addons.d.ts.map +1 -0
  650. package/node_modules/@noble/hashes/sha3-addons.js +402 -0
  651. package/node_modules/@noble/hashes/sha3-addons.js.map +1 -0
  652. package/node_modules/@noble/hashes/sha3.d.ts +53 -0
  653. package/node_modules/@noble/hashes/sha3.d.ts.map +1 -0
  654. package/node_modules/@noble/hashes/sha3.js +239 -0
  655. package/node_modules/@noble/hashes/sha3.js.map +1 -0
  656. package/node_modules/@noble/hashes/sha512.d.ts +26 -0
  657. package/node_modules/@noble/hashes/sha512.d.ts.map +1 -0
  658. package/node_modules/@noble/hashes/sha512.js +29 -0
  659. package/node_modules/@noble/hashes/sha512.js.map +1 -0
  660. package/node_modules/@noble/hashes/src/_assert.ts +22 -0
  661. package/node_modules/@noble/hashes/src/_blake.ts +50 -0
  662. package/node_modules/@noble/hashes/src/_md.ts +176 -0
  663. package/node_modules/@noble/hashes/src/_u64.ts +91 -0
  664. package/node_modules/@noble/hashes/src/argon2.ts +497 -0
  665. package/node_modules/@noble/hashes/src/blake1.ts +534 -0
  666. package/node_modules/@noble/hashes/src/blake2.ts +486 -0
  667. package/node_modules/@noble/hashes/src/blake2b.ts +10 -0
  668. package/node_modules/@noble/hashes/src/blake2s.ts +20 -0
  669. package/node_modules/@noble/hashes/src/blake3.ts +272 -0
  670. package/node_modules/@noble/hashes/src/crypto.ts +9 -0
  671. package/node_modules/@noble/hashes/src/cryptoNode.ts +15 -0
  672. package/node_modules/@noble/hashes/src/eskdf.ts +187 -0
  673. package/node_modules/@noble/hashes/src/hkdf.ts +88 -0
  674. package/node_modules/@noble/hashes/src/hmac.ts +94 -0
  675. package/node_modules/@noble/hashes/src/index.ts +31 -0
  676. package/node_modules/@noble/hashes/src/legacy.ts +293 -0
  677. package/node_modules/@noble/hashes/src/pbkdf2.ts +122 -0
  678. package/node_modules/@noble/hashes/src/ripemd160.ts +12 -0
  679. package/node_modules/@noble/hashes/src/scrypt.ts +257 -0
  680. package/node_modules/@noble/hashes/src/sha1.ts +10 -0
  681. package/node_modules/@noble/hashes/src/sha2.ts +402 -0
  682. package/node_modules/@noble/hashes/src/sha256.ts +24 -0
  683. package/node_modules/@noble/hashes/src/sha3-addons.ts +499 -0
  684. package/node_modules/@noble/hashes/src/sha3.ts +258 -0
  685. package/node_modules/@noble/hashes/src/sha512.ts +34 -0
  686. package/node_modules/@noble/hashes/src/utils.ts +395 -0
  687. package/node_modules/@noble/hashes/utils.d.ts +161 -0
  688. package/node_modules/@noble/hashes/utils.d.ts.map +1 -0
  689. package/node_modules/@noble/hashes/utils.js +313 -0
  690. package/node_modules/@noble/hashes/utils.js.map +1 -0
  691. package/package.json +179 -8
  692. package/schemas/catalog.schema.json +357 -0
  693. package/src/align.ts +239 -0
  694. package/src/audio-init-parser.ts +189 -0
  695. package/src/audio-ring-buffer.ts +120 -0
  696. package/src/authored-timing.ts +63 -0
  697. package/src/block-policy.ts +903 -0
  698. package/src/carp-catalog.ts +1086 -0
  699. package/src/catalog-fec-params.ts +803 -0
  700. package/src/catalog-network-source.ts +74 -0
  701. package/src/catalog-validator.ts +34 -0
  702. package/src/cmaf-block-assembler.ts +1255 -0
  703. package/src/cmaf-group-batcher.ts +104 -0
  704. package/src/cmcd-producer.ts +329 -0
  705. package/src/codec-utils.ts +1984 -0
  706. package/src/conceal-timeline.ts +293 -0
  707. package/src/delivery-gap.ts +147 -0
  708. package/src/duplicate-ledger.ts +372 -0
  709. package/src/fec-codec.ts +61 -0
  710. package/src/fec-manager.ts +4241 -0
  711. package/src/fec-starvation-detector.ts +128 -0
  712. package/src/fec-state.ts +228 -0
  713. package/src/fec-worker-setup.ts +291 -0
  714. package/src/fmp4-completion.ts +47 -0
  715. package/src/fmp4-reader.ts +112 -0
  716. package/src/index.ts +592 -21
  717. package/src/iso-block-locator.ts +329 -0
  718. package/src/iso-bmff-timing.ts +813 -0
  719. package/src/loc.ts +128 -154
  720. package/src/manifest-auth-plan.ts +107 -0
  721. package/src/media-router.ts +841 -0
  722. package/src/mfu-reassembler.ts +3480 -155
  723. package/src/mfu-reassembly-policy.ts +134 -0
  724. package/src/mmtp-container-parser.ts +2406 -0
  725. package/src/mmtp-decode-pipeline.ts +406 -0
  726. package/src/mmtp-router.ts +4712 -0
  727. package/src/mmtp-to-cmaf.ts +977 -0
  728. package/src/multicast-auth-catalog.ts +340 -0
  729. package/src/multicast-input.ts +793 -0
  730. package/src/multicast-manager.ts +2895 -0
  731. package/src/multicast-transport.ts +1058 -0
  732. package/src/multicast-unwrap.ts +132 -0
  733. package/src/no-modules.ts +21 -0
  734. package/src/phase14-catalog-override.ts +336 -0
  735. package/src/repair-fetch.ts +786 -0
  736. package/src/repair-layers.ts +553 -0
  737. package/src/sample-combiner.ts +938 -0
  738. package/src/signaling.ts +78 -0
  739. package/src/source-auth.ts +1 -0
  740. package/src/switching-set-alignment.ts +109 -0
  741. package/src/timestamp-codec.ts +265 -0
  742. package/src/track-pipeline-setup.ts +205 -0
  743. package/src/track-pipeline.ts +332 -0
  744. package/src/track-session.ts +1010 -0
  745. package/src/transport-pool.ts +128 -0
  746. package/src/wasm-mfu-reassembler.ts +405 -0
  747. package/src/wasm-mmtp-container-parser.ts +23 -0
  748. package/test-vectors/align.json +199 -0
  749. package/test-vectors/catalog/README.md +123 -0
  750. package/test-vectors/catalog/negative/archive-origin-with-path.json +33 -0
  751. package/test-vectors/catalog/negative/archive-unknown-field.json +34 -0
  752. package/test-vectors/catalog/negative/fec-block-profile-missing.json +51 -0
  753. package/test-vectors/catalog/negative/fec-block-profile-retired.json +52 -0
  754. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +52 -0
  755. package/test-vectors/catalog/negative/fec-enhancement-repair-removed.json +28 -0
  756. package/test-vectors/catalog/negative/fec-repair-layer-geometry.json +33 -0
  757. package/test-vectors/catalog/negative/fec-repair-layer-missing-symbols.json +31 -0
  758. package/test-vectors/catalog/negative/fec-repair-multiple-depends.json +32 -0
  759. package/test-vectors/catalog/negative/fec-repair-overlay-with-layer.json +34 -0
  760. package/test-vectors/catalog/negative/fec-repair-priority-out-of-band.json +24 -0
  761. package/test-vectors/catalog/negative/fec-repair-source-symbols-without-scope.json +33 -0
  762. package/test-vectors/catalog/negative/legacy-selection-params.json +15 -0
  763. package/test-vectors/catalog/negative/media-track-repair-layer.json +16 -0
  764. package/test-vectors/catalog/negative/missing-mmtp-fields.json +12 -0
  765. package/test-vectors/catalog/negative/multicast-auth-padded-key.json +37 -0
  766. package/test-vectors/catalog/negative/multicast-auth-reused-track-format.json +53 -0
  767. package/test-vectors/catalog/negative/multicast-auth-trailing-pad-bits.json +37 -0
  768. package/test-vectors/catalog/negative/multicast-endpoint-missing-protocol-and-source.json +24 -0
  769. package/test-vectors/catalog/negative/multicast-network-source-empty.json +44 -0
  770. package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
  771. package/test-vectors/catalog/negative/network-source-object.json +25 -0
  772. package/test-vectors/catalog/negative/raptorq-source-symbols-over-max.json +24 -0
  773. package/test-vectors/catalog/negative/raptorq-unaligned-symbol.json +27 -0
  774. package/test-vectors/catalog/negative/repair-track-legacy-shape.json +19 -0
  775. package/test-vectors/catalog/negative/track-role-empty.json +16 -0
  776. package/test-vectors/catalog/negative/track-role-non-string.json +16 -0
  777. package/test-vectors/catalog/positive/archive-origin.json +34 -0
  778. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +52 -0
  779. package/test-vectors/catalog/positive/fec-layered-repair.json +106 -0
  780. package/test-vectors/catalog/positive/fec-multicast.json +53 -0
  781. package/test-vectors/catalog/positive/flat-av.json +30 -0
  782. package/test-vectors/catalog/positive/multicast-auth-rotation.json +55 -0
  783. package/test-vectors/catalog/positive/multicast-native-ssm-no-network-source.json +44 -0
  784. package/test-vectors/catalog/positive/ticks-and-mixed-timescales.json +39 -0
  785. package/test-vectors/catalog/positive/track-role.json +49 -0
  786. package/test-vectors/catalog/releases/moqcast-native-v16-v1/catalog.json +65 -0
  787. package/test-vectors/catalog/releases/moqcast-native-v16-v1.archive.sha256 +1 -0
  788. package/test-vectors/catalog-multicast-auth-v1.json +26 -0
  789. package/test-vectors/catalog-validation.json +767 -0
  790. package/test-vectors/catalog-validator-public-api.mjs +25 -0
  791. package/test-vectors/generate-source-auth-fixture.mjs +114 -0
  792. package/test-vectors/hevc-x265-repeat-headers-v1.json +40 -0
  793. package/test-vectors/source-auth-v1.json +61 -0
  794. package/test-vectors/source-contiguity-v1.json +131 -0
  795. package/test-vectors/subsample-placement-v1.json +230 -0
  796. package/dist/mmtp.d.ts +0 -73
  797. package/dist/mmtp.d.ts.map +0 -1
  798. package/dist/mmtp.js +0 -210
  799. package/dist/mmtp.js.map +0 -1
  800. package/src/mmtp.ts +0 -277
@@ -0,0 +1,4241 @@
1
+ /**
2
+ * FEC Manager — codec-agnostic FEC decode service.
3
+ *
4
+ * Receives (packetId, sbn, esi, symbolData) tuples from any transport
5
+ * (MMTP, LOC, etc.) and manages FEC block lifecycle: source counting,
6
+ * WASM RaptorQ decode, block timeout, and recovery/failure notification.
7
+ *
8
+ * Extracted from MulticastManager to decouple FEC block logic from
9
+ * MMTP packet parsing and frame routing.
10
+ */
11
+
12
+ import { computeFecDeliveryWindowMs } from './track-session.js'
13
+ import { DeliveryGapEstimator } from './delivery-gap.js'
14
+ import {
15
+ deriveFecInterleaveDepth,
16
+ deriveFecRetentionBlocks,
17
+ tryDeriveFecRetentionBlocks,
18
+ } from '@blockcast/mmt-fec'
19
+ import {
20
+ isoBlockContains,
21
+ isoBlocksBehindLowerBound,
22
+ parseFecBlockProfile,
23
+ serial32Distance,
24
+ serial32Precedes,
25
+ ssbg1FitsSymbol,
26
+ type FecBlockProfile,
27
+ } from '@blockcast/mmt-base'
28
+ import { IsoBlockLocator, type IsoRepairPlacement } from './iso-block-locator.js'
29
+ import { MIN_INTERLEAVE_DEPTH_MS } from './fec-state.js'
30
+ import {
31
+ BlockClassifier,
32
+ type BlockClass,
33
+ type BlockClassifierGeometry,
34
+ type ClassifierChange,
35
+ type ClassifierMode,
36
+ type ClassifierReason,
37
+ type ReclassificationEvidence,
38
+ type SourceSymbolEvidence,
39
+ type TrackKind,
40
+ } from './block-policy.js'
41
+
42
+ import type { MmtpDeliveryProvenance } from './mfu-reassembler.js'
43
+ import type {
44
+ FecWorkerClient,
45
+ FecTrackStats,
46
+ FecBlockSnapshot,
47
+ FrameMeta,
48
+ FecWorkerErrorCode,
49
+ } from '@blockcast/fec-worker'
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // Constants
53
+ // ---------------------------------------------------------------------------
54
+
55
+ // MIN_INTERLEAVE_DEPTH_MS lives with the catalog FEC predicate that also
56
+ // needs it (fec-state.ts); re-exported here for existing importers.
57
+ export { MIN_INTERLEAVE_DEPTH_MS }
58
+ const WORKER_ERROR_LOG_CAP = 5
59
+ const WORKER_ERROR_KIND_CAP = 32
60
+ const WORKER_ERROR_OVERFLOW_KIND = 'other'
61
+ const STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Types
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Algorithm-agnostic FEC decoder backend interface.
69
+ *
70
+ * Implementations:
71
+ * - RaptorQ WASM (mmt_wasm.js) — RFC 6330
72
+ * - Reed-Solomon WASM — future
73
+ * - XOR — future
74
+ *
75
+ * Source/repair symbol IDs follow ISO 23008-1 §C.5.2/C.5.3:
76
+ * source: SS_ID (flat 32-bit symbol identifier)
77
+ * repair: SS_Start + SSB_length + RS_ID (block-scoped repair coords)
78
+ */
79
+ export type WasmFecDecoder = {
80
+ add_source(ss_id: number, data: Uint8Array, ts: number): Uint8Array | null
81
+ add_repair(ss_start: number, ssb_length: number, rs_id: number, data: Uint8Array, ts: number): Uint8Array | null
82
+ configure(oti: Uint8Array): void
83
+ cleanup(current_time: number): Uint8Array
84
+ /** Retire the named blocks from the decoder (last-chance decode + stats). */
85
+ cleanup_blocks_detailed(ss_starts: Uint32Array): unknown
86
+ /**
87
+ * iso-ssbg1-v1 only: retire the source symbols the decoder holds before a
88
+ * repair states their block, once no repair can place them any more, by the
89
+ * decoder's own horizon behind `current`, the newest SS_ID seen. Retires no
90
+ * block: the manager retires blocks itself, by their deadlines. Returns how
91
+ * many it retired. The manager calls it after every feed that grows the
92
+ * decoder and on block retirement. (`MmtFecDecoder.retire_unplaced`; the
93
+ * worker path uses `cleanup_by_ss_start`, which applies the same rule.)
94
+ */
95
+ retire_unplaced(current: number): number
96
+ flush?(): void
97
+ reset_stats?(): void
98
+ }
99
+
100
+ /** Algorithm-agnostic FEC stats snapshot. */
101
+ export interface FecStats {
102
+ sourcePackets: number
103
+ repairPackets: number
104
+ duplicateSymbols: number
105
+ blocksClean: number
106
+ blocksRecovered: number
107
+ blocksFailed: number
108
+ blocksComplete: number
109
+ mixedPathBlocks: number
110
+ recentBlockPathCounts: FecBlockPathCount[]
111
+ k: number
112
+ /** Of blocks with loss, what percentage were recovered (0-100). */
113
+ recoveryRate: number
114
+ /** What percentage of blocks had any loss (0-100). */
115
+ packetLossRate: number
116
+ /** Per-MMTP-packet-ID counters for the synchronous WASM decoder path. */
117
+ tracks: FecPacketStats[]
118
+ /** Latest Worker/WASM snapshot for each packet ID. */
119
+ workers: Array<FecTrackStats & { packetId: number }>
120
+ /** Main-thread repair symbols rejected before dispatch because their size did not match T. */
121
+ repairSymbolSizeMismatches: number
122
+ /** Bounded Worker error counts keyed by stable code, or message text for legacy errors. */
123
+ workerErrors: Record<string, number>
124
+ }
125
+
126
+ export interface FecPacketStats {
127
+ packetId: number
128
+ sourcePackets: number
129
+ repairPackets: number
130
+ duplicateSymbols: number
131
+ blocksClean: number
132
+ blocksRecovered: number
133
+ blocksFailed: number
134
+ blocksComplete: number
135
+ k: number
136
+ recoveryRate: number
137
+ packetLossRate: number
138
+ }
139
+
140
+ export type FecSymbolSource = 'multicast' | 'moq'
141
+
142
+ /**
143
+ * One iso-ssbg1-v1 first-arrival source symbol MmtpRouter holds until a repair
144
+ * symbol states its block: the exact protected packet (no SS_ID, unpadded),
145
+ * the transport that delivered it and its classification evidence.
146
+ */
147
+ export interface IsoHeldSource {
148
+ readonly symbolData: Uint8Array
149
+ readonly source: FecSymbolSource
150
+ readonly evidence: SourceSymbolEvidence
151
+ /** Larger than one ssbg_mode1 symbol: counted, never decoded. */
152
+ readonly oversized: boolean
153
+ }
154
+
155
+ /**
156
+ * How the multicast leg hands its symbols to this manager.
157
+ *
158
+ * - `'datagram'`: every symbol is an independent datagram from the receiving
159
+ * socket. A pause in arrivals is the only loss signal the receiver has, so a
160
+ * block that stays idle past the catalog-derived inactivity deadline fails.
161
+ * - `'ordered-relay'`: the provider relays one receiving socket over a
162
+ * reliable, ordered stream (the BCDS bridge's WebTransport uni stream). The
163
+ * delivered sequence is a subsequence of the socket's receive order, so a
164
+ * pause carries no loss information at all: the relay's own scheduling
165
+ * decides when bytes arrive. What does carry it is order. Once the stream
166
+ * has advanced more than the decoder's interleave horizon past a block, no
167
+ * symbol of that block can still be in flight, and the block's fate follows
168
+ * from the symbols it holds (in-band SS_ID/SS_Start and SSB_length), not
169
+ * from a wall clock tuned for raw datagrams.
170
+ *
171
+ * Only the provider can know which of the two it is delivering; an undeclared
172
+ * provider promises no ordering and keeps datagram semantics.
173
+ */
174
+ export type MulticastSymbolDelivery = 'datagram' | 'ordered-relay'
175
+
176
+ function isMulticastSymbolDelivery(value: unknown): value is MulticastSymbolDelivery {
177
+ return value === 'datagram' || value === 'ordered-relay'
178
+ }
179
+
180
+ export interface FecBlockPathCount {
181
+ packetId: number
182
+ sbn: number
183
+ catalogTrackName?: string
184
+ multicastSymbols: number
185
+ moqSymbols: number
186
+ complete: boolean
187
+ }
188
+
189
+ type FecLifecycleTrace = {
190
+ atMs: number
191
+ event:
192
+ | 'repair-requested'
193
+ | 'repair-arrived'
194
+ | 'timeout-queued'
195
+ | 'horizon-settled'
196
+ | 'cleanup-ack'
197
+ | 'cleanup-ack-timeout'
198
+ | 'recovered'
199
+ | 'failed'
200
+ | 'decoder-unavailable'
201
+ packetId: number
202
+ sbn: number
203
+ catalogTrackName?: string
204
+ sourceCount: number
205
+ sourceEsis: number[]
206
+ repairRsIds: number[]
207
+ decoderPath: 'worker' | 'sync' | 'none'
208
+ deadlineRemainingMs?: number
209
+ pendingCleanup: boolean
210
+ rsId?: number
211
+ }
212
+
213
+ export interface FECManagerConfig {
214
+ /**
215
+ * The catalog `fec.blockProfile` of the track (BLO-35597). Required for every
216
+ * configured track: there is no default, and nothing infers it. The only
217
+ * profile is `iso-ssbg1-v1`: ISO/IEC 23008-1 ssbg_mode1 with K' = SSB_length
218
+ * blocks keyed by SS_Start and located by `(SS_Start, SSB_length)` range
219
+ * membership, `k` being only their maximum. The retired `k-padded-v1` token
220
+ * is refused.
221
+ */
222
+ blockProfile?: FecBlockProfile
223
+ k?: number
224
+ /** Symbol size in bytes (T). NOT repair count. */
225
+ symbolSize?: number
226
+ interleaveDepthMs?: number
227
+ fps?: number
228
+ /** Guarded block inactivity deadline derived from the full delivery geometry. */
229
+ timeoutMs?: number
230
+ /** Media kind of the track (block class `audio` vs video classification). */
231
+ trackKind?: TrackKind
232
+ /** Catalog codec string. */
233
+ codec?: string
234
+ /**
235
+ * Block classifier geometry derived from raw catalog timing
236
+ * (`deriveBlockClassifierGeometry`). Absent geometry classifies every video
237
+ * block `unknown` (fail-closed: protected).
238
+ */
239
+ geometry?: BlockClassifierGeometry
240
+ }
241
+
242
+ interface ResolvedFECTrackConfig {
243
+ blockProfile?: FecBlockProfile
244
+ k: number
245
+ symbolSize: number
246
+ interleaveDepthMs: number
247
+ timeoutMs: number
248
+ fps?: number
249
+ trackKind?: TrackKind
250
+ codec?: string
251
+ geometry?: BlockClassifierGeometry
252
+ }
253
+
254
+ /** Which symbol path completed a short block. */
255
+ export type RepairVia = 'inband' | 'quic'
256
+
257
+ /** Lifecycle resolution of one FEC block, for in-order frame release. */
258
+ export type FecBlockResolution = 'pending' | 'complete' | 'failed' | 'untracked'
259
+
260
+ interface MutableFecCounters {
261
+ sourcePackets: number
262
+ repairPackets: number
263
+ duplicateSymbols: number
264
+ blocksClean: number
265
+ blocksRecovered: number
266
+ blocksFailed: number
267
+ }
268
+
269
+ function newFecCounters(): MutableFecCounters {
270
+ return {
271
+ sourcePackets: 0,
272
+ repairPackets: 0,
273
+ duplicateSymbols: 0,
274
+ blocksClean: 0,
275
+ blocksRecovered: 0,
276
+ blocksFailed: 0,
277
+ }
278
+ }
279
+
280
+ /**
281
+ * The one timer armed for a block deadline (BLO-36599).
282
+ *
283
+ * Symbols move a block's deadline later many times per block. Re-arming a
284
+ * browser timer for each of them cost ~41 us per clear+set pair on a Kirin 659,
285
+ * so the deadline itself is stored as a performance.now() timestamp and this
286
+ * timer only guarantees a wake-up no later than it. When the timer fires it
287
+ * re-checks the stored deadline and re-arms for the remainder if activity
288
+ * moved it. `fireAtMs` is what the armed timer was scheduled for; `handle` is
289
+ * null once it fired without re-arming.
290
+ */
291
+ interface DeadlineTimer {
292
+ handle: ReturnType<typeof setTimeout> | null
293
+ fireAtMs: number
294
+ }
295
+
296
+ /**
297
+ * Delete the `count` oldest (first-inserted) keys of `collection` in place
298
+ * and return them.
299
+ */
300
+ function dropOldest(
301
+ collection: Set<string> | Map<string, unknown>,
302
+ count: number,
303
+ ): string[] {
304
+ const dropped: string[] = []
305
+ for (const key of collection.keys()) {
306
+ if (dropped.length >= count) break
307
+ dropped.push(key)
308
+ }
309
+ for (const key of dropped) collection.delete(key)
310
+ return dropped
311
+ }
312
+
313
+ /** A block key whose terminal state expires at `expiresAtMs`. */
314
+ interface TerminalRecord {
315
+ readonly key: string
316
+ readonly expiresAtMs: number
317
+ }
318
+
319
+ /** FIFO of terminal records in the order blocks became terminal. */
320
+ class TerminalQueue {
321
+ #records: TerminalRecord[] = []
322
+ #head = 0
323
+
324
+ push(record: TerminalRecord): void {
325
+ this.#records.push(record)
326
+ }
327
+
328
+ peek(): TerminalRecord | undefined {
329
+ return this.#records[this.#head]
330
+ }
331
+
332
+ shift(): void {
333
+ this.#head++
334
+ // Compact once the consumed prefix outweighs the live tail, so the array
335
+ // never holds more than twice the records still in the window.
336
+ if (this.#head * 2 >= this.#records.length) {
337
+ this.#records = this.#records.slice(this.#head)
338
+ this.#head = 0
339
+ }
340
+ }
341
+ }
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // FECManager
345
+ // ---------------------------------------------------------------------------
346
+
347
+ /** Why a stream's Worker decoder stopped being routable. */
348
+ export type FecDecoderUnavailableReason = 'cleared' | 'disposed'
349
+
350
+ /**
351
+ * What still decodes a stream after its Worker left routing: the synchronous
352
+ * WASM decoder registered for the same stream (the Worker path took precedence
353
+ * over it while both were live), or nothing.
354
+ */
355
+ export type FecFallbackDecoder = 'sync' | 'none'
356
+
357
+ export interface FecDecoderUnavailableEvent {
358
+ readonly packetId: number
359
+ readonly catalogTrackName?: string
360
+ readonly reason: FecDecoderUnavailableReason
361
+ /**
362
+ * What decodes the stream at the moment the Worker left. A synchronous
363
+ * decoder discarded later (a resetTrack flush failure drops it without an
364
+ * event) is not reported here; a consumer that keeps a stream alive on
365
+ * 'sync' owns that decoder's lifecycle itself.
366
+ */
367
+ readonly fallbackDecoder: FecFallbackDecoder
368
+ }
369
+
370
+ export class FECManager {
371
+ // Per-track WASM RaptorQ decoders, keyed by physical stream identity.
372
+ #fecDecoders = new Map<string, { client: WasmFecDecoder; k: number }>()
373
+ /** @deprecated Use setFecDecoder(packetId, ...). Backwards-compat shim. */
374
+
375
+ // Per-track Worker-backed FEC decoders, keyed by physical stream identity.
376
+ // Worker-backed tracks use async decode — recovered frames arrive via onFrame callback,
377
+ // not synchronous return from feedSourceSymbol/feedRepairSymbol.
378
+ #workerClients = new Map<string, FecWorkerClient>()
379
+ // Worker clients whose streams releasePacket ended. A Worker posts
380
+ // asynchronously, so a message it sent before its reset can still arrive;
381
+ // the stream it describes is gone, and letting it in would rebuild state
382
+ // (block ledgers, statistics, lifecycle events) for a retired packet ID.
383
+ #releasedWorkerClients = new WeakSet<FecWorkerClient>()
384
+ // Worker setup can finish while an interleaved block is already collecting
385
+ // on the sync decoder. Keep that block on its original decoder so later
386
+ // source/repair symbols do not split across two RaptorQ states.
387
+ #syncDecoderBlockOwners = new Map<string, WasmFecDecoder>()
388
+ #decoderBlockOwners = new WeakMap<object, Map<number, {
389
+ catalogTrackName?: string
390
+ conflicted: boolean
391
+ }>>()
392
+
393
+ #fecK = 4
394
+ #fecSymbolSize = 0
395
+ #fecTimeoutMs = 500 // default 500ms; refined by setFramerate() when fps known
396
+ #trackConfigs = new Map<number, ResolvedFECTrackConfig>()
397
+ #fecStats = newFecCounters()
398
+ #fecTrackStats = new Map<number, MutableFecCounters>()
399
+ #fecWorkerStats = new Map<number, FecTrackStats>()
400
+ #fecStatsObservers = new Set<(packetId: number, stats: FecTrackStats) => void>()
401
+
402
+ // Block inactivity tracking: (packetId, SBN) -> the one armed timer. The
403
+ // deadline is derived from catalog geometry and refreshed on progress; only
404
+ // an idle block fails. #activeBlockDeadlinesMs is the authoritative
405
+ // deadline; the timer re-checks it when it fires (see DeadlineTimer).
406
+ #activeBlocks = new Map<string, DeadlineTimer>()
407
+ #activeBlockDeadlinesMs = new Map<string, number>()
408
+ // The two terms #activeBlockDeadlinesMs is the later of (BLO-35597):
409
+ // - the multicast late-symbol wait, refreshed by every accepted symbol;
410
+ // - a D-28 repair hold, set by the repair scheduler only while a repair
411
+ // FETCH it admitted can still land before the block's presentation
412
+ // deadline. The multicast span elapsing never ends a fetch the scheduler
413
+ // judged able to arrive in time.
414
+ #blockWaitDeadlinesMs = new Map<string, number>()
415
+ #repairHoldUntilMs = new Map<string, number>()
416
+ // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
417
+ // term (see DeliveryGapEstimator for the statistic and why).
418
+ #deliveryGaps = new DeliveryGapEstimator()
419
+ #lifecycleTrace: FecLifecycleTrace[] = []
420
+ // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
421
+ // Failure remains pending until cleanupComplete acknowledges that queue drain.
422
+ #pendingWorkerCleanups = new Set<string>()
423
+ #pendingWorkerCleanupClients = new Map<string, FecWorkerClient>()
424
+ // One bound per owed cleanup: the acknowledgement is awaited for at most one
425
+ // catalog-derived block lifetime (fail bound plus repair grace).
426
+ // A Worker that hangs or drops one message must not leave the block
427
+ // 'pending' forever, which would park every later frame of its stream in
428
+ // the in-order release gate. Each entry owns its handle; the callback
429
+ // checks it still owns the key, so a settled or reset key is never touched.
430
+ #pendingWorkerCleanupBounds = new Map<string, { handle: ReturnType<typeof setTimeout> }>()
431
+ // Source symbol count per track-scoped block — marks complete when K symbols arrive.
432
+ #blockSourceCounts = new Map<string, number>()
433
+ #blockSourceEsis = new Map<string, Set<number>>()
434
+ // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
435
+ // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
436
+ // media units, usually before it holds K symbols; under iso-ssbg1-v1
437
+ // (ssbg_mode1) that block is K' = SSB_length symbols, its repair ESIs start
438
+ // at SSB_length, and K is only the maximum. Such a block is clean at
439
+ // SSB_length source arrivals and recoverable from SSB_length received
440
+ // symbols; waiting for K fails every one of them.
441
+ #blockAuthoredLengths = new Map<string, number>()
442
+ #ssbLengthConflictCount = 0
443
+ #blockRepairRsIds = new Map<string, Set<number>>()
444
+ // Blocks already recovered — prevents late source symbols from restarting timeouts.
445
+ // WASM removes blocks after recovery; late symbols create empty blocks returning null,
446
+ // which would falsely start new timeouts without this guard.
447
+ //
448
+ // Every insertion goes through #markTerminal, which retires the key once its
449
+ // catalog-derived retention window (terminalRetentionMsForPacket) passes. The
450
+ // previous bound (trim to 500 at 1000) lived in cancelBlockTimeout alone, so
451
+ // a stream whose blocks only failed grew this set without limit (BLO-36599).
452
+ #completedBlocks = new Set<string>()
453
+ #terminalExpiryMs = new Map<string, number>()
454
+ #terminalQueues = new Map<number, TerminalQueue>()
455
+ // sbn -> (block key -> packetId) for every key held by #activeBlocks,
456
+ // #blockSourceCounts, #blockCatalogTrackNames or #completedBlocks. A lookup
457
+ // without a catalog name used to string-parse every key of all of those on
458
+ // each source packet, which is O(retained blocks) per packet (BLO-36599).
459
+ #blockKeysBySbn = new Map<number, Map<string, number>>()
460
+ // Stable per-name encodings for stream and block keys, bounded by the
461
+ // catalog's track names; #blockKey is built several times per packet.
462
+ #encodedTrackNames = new Map<string, string>()
463
+ // The last block and stream key built. One packet asks for the same block's
464
+ // key from every FECManager entry point it passes through (~6 per source
465
+ // symbol), so each key is built once per packet rather than once per call
466
+ // (BLO-36599). Both keys are pure functions of their arguments.
467
+ #lastBlockKeySbn = -1
468
+ #lastBlockKeyPacketId = -1
469
+ #lastBlockKeyTrackName: string | undefined = undefined
470
+ #lastBlockKey = ''
471
+ #lastStreamKeyPacketId = -1
472
+ #lastStreamKeyTrackName: string | undefined = undefined
473
+ #lastStreamKey = ''
474
+ #seenSymbols = new Set<string>()
475
+ #blockPathCounts = new Map<string, FecBlockPathCount>()
476
+ // Receiver-local first-accepted-symbol time per block, bounded like
477
+ // #blockPathCounts (see blockAnchorAtMs).
478
+ #blockAnchorsMs = new Map<string, number>()
479
+ // Exact catalog identity observed on accepted symbols for each FEC block.
480
+ // Conflicting identities collapse to null so recovery fails closed.
481
+ #blockCatalogTrackNames = new Map<string, string | null>()
482
+ // A receiver joins an already-running live stream in the middle of D
483
+ // interleaved source blocks. This applies to both multicast and reliable MoQ:
484
+ // a MoQ group boundary is not an FEC ESI=0 boundary. Those blocks are not
485
+ // packet loss because their earlier ESIs predate the subscription. Ignore
486
+ // each such block until ESI=0 establishes a complete boundary for the track.
487
+ // After that boundary, a first observed ESI>0 is real delivery loss and must
488
+ // continue through normal FEC recovery/failure accounting.
489
+ #startupAlignedPackets = new Set<string>()
490
+ #startupPartialBlocks = new Set<string>()
491
+ // A live multicast join can observe an ESI=0 source boundary before the
492
+ // repair lane catches up. Returning false here also drops that media packet
493
+ // at MmtpRouter, so the readiness probe is multicast-only and bounded: an
494
+ // actual multicast repair unlocks the next boundary, while a second source
495
+ // boundary fails open. Reliable MoQ media continues through normal startup
496
+ // alignment and retained MoQ repair cannot prove multicast readiness.
497
+ #startupRequireRepairReady = false
498
+ #startupRepairReadyPackets = new Set<string>()
499
+ #startupRepairBoundaryCounts = new Map<string, number>()
500
+ #startupRepairFailOpenPackets = new Set<string>()
501
+ // SBNs that reached K source-symbol arrivals via trackBlock. Used by the
502
+ // worker recovery suppression check (see onFrame handler below) so we only
503
+ // suppress `recovered=true` emits for blocks that ALSO completed cleanly
504
+ // via source symbols. Separating this from #completedBlocks (which is also
505
+ // populated by every worker frame emit, by failed timeouts, and by external
506
+ // callers) was the BLO-3323 L15 fix: the prior predicate caused blocksRecovered
507
+ // to stay at 0 because the SBN was always in #completedBlocks by the time the
508
+ // worker fired recovered=true.
509
+ #cleanlyCompletedBlocks = new Set<string>()
510
+ // D-28: blocks whose repair deadline already fired onRepairNeeded. At most
511
+ // one repair request per block; entries are removed when the block
512
+ // completes, recovers, or fails.
513
+ #repairRequestedBlocks = new Set<string>()
514
+ // D-28: repair deadlines refreshed by accepted source progress until the
515
+ // first repair request. A `null` value marks a deadline that already fired
516
+ // and requested repair (never re-armed). At most K accepted source symbols
517
+ // can refresh the horizon, so browser scheduling delay cannot create an
518
+ // early loss signal and repair traffic cannot keep a block alive
519
+ // indefinitely. #repairDeadlineAtMs is the authoritative deadline; the one
520
+ // armed timer re-checks it when it fires (see DeadlineTimer).
521
+ #repairDeadlines = new Map<string, DeadlineTimer | null>()
522
+ #repairDeadlineAtMs = new Map<string, number>()
523
+ // Worker recovery emits all K source symbols. Track recovery once per block
524
+ // while routing only ESI slots that were absent from the direct source path.
525
+ #workerRecoveredBlocks = new Set<string>()
526
+
527
+ // How the multicast leg delivers symbols (see MulticastSymbolDelivery). The
528
+ // provider declares it per transport join; absence keeps datagram semantics.
529
+ #multicastSymbolDelivery: MulticastSymbolDelivery = 'datagram'
530
+ // ordered-relay: per stream, the highest SBN any multicast symbol carried.
531
+ // The relay preserves the receiving socket's order, so every block more than
532
+ // the decoder's interleave horizon behind this frontier has received every
533
+ // symbol it will ever receive over multicast.
534
+ #orderedFrontiers = new Map<string, number>()
535
+ // ordered-relay: blocks with multicast symbols that are neither terminal nor
536
+ // handed to a decoder cleanup, per stream, keyed by SBN. They carry no
537
+ // timer; the frontier settles them. At most one interleave horizon of blocks
538
+ // per stream is ever here.
539
+ #orderedPendingBlocks = new Map<string, Map<number, string>>()
540
+
541
+ // ── Keyframe-protected repair policy (block-policy.ts) ──
542
+ // One classifier per physical stream, built from that stream's geometry.
543
+ #classifiers = new Map<string, BlockClassifier>()
544
+ // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
545
+ // rungs can share a packetId with a different framerate or GOP, so the
546
+ // packet-level geometry is only the geometry of a packet whose streams
547
+ // were never configured apart (see #geometryFor).
548
+ #streamGeometries = new Map<string, BlockClassifierGeometry>()
549
+ // Terminal outcomes retained for in-order frame release: a failed block is
550
+ // resolved-with-loss, a completed one resolved-clean.
551
+ #failedBlocks = new Set<string>()
552
+ // A block's class at resolution, so events emitted after the classifier
553
+ // forgot the block (the router counts a recovery after cancelling the
554
+ // block) still carry it.
555
+ #resolvedBlockClasses = new Map<string, BlockClass>()
556
+ // Blocks already reported through onBlockRepaired (once per block).
557
+ #repairedBlocks = new Set<string>()
558
+ // Blocks created before any symbol of theirs was tracked: the repair-less
559
+ // spans placeIsoRepair materializes (onBlockVanished).
560
+ #materializedBlocks = new Set<string>()
561
+ // packetIds whose ordered-relay horizon became underivable and fell back to
562
+ // the datagram deadline. Bounds the warn in #derivableOrderedHorizon to once
563
+ // per stream. Not only throws: the ordinary out-of-range case is detected by
564
+ // arithmetic and never throws at all.
565
+ #orderedHorizonWarnedFor = new Set<number>()
566
+ // Newest block start (SS_Start) seen per stream and when: the frontier for
567
+ // source-discontinuity detection and isoSpanResolution.
568
+ #highestSbn = new Map<string, { sbn: number; atMs: number }>()
569
+ // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
570
+ // block only once a repair symbol stated the block's (SS_Start, SSB_length).
571
+ #isoLocators = new Map<string, IsoBlockLocator<IsoHeldSource>>()
572
+ #isoRepairRefusedCount = 0
573
+ #isoSourceOversizeCount = 0
574
+ // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
575
+ // only a stream whose SS_IDs are not consecutive reaches it. Cumulative,
576
+ // unlike the locators, which a reset discards.
577
+ #isoHeldEvictedCount = 0
578
+ // Sources a synchronous decoder held unplaced and retired at its horizon
579
+ // (WasmFecDecoder.retire_unplaced): placed sources whose block's repair
580
+ // never reached that decoder. Cumulative.
581
+ #isoDecoderUnplacedRetired = 0
582
+ // Failed retire_unplaced calls. The sweep runs on every feed, so its warn is
583
+ // rate-limited like the other per-symbol warns here. Cumulative.
584
+ #isoDecoderUnplacedRetireFailed = 0
585
+ // The latest source symbol per stream that carried its MMTP
586
+ // packet_sequence_number: the anchor that bounds how many blocks the
587
+ // producer can have started before a later source symbol.
588
+ #sourceAnchors = new Map<string, { sbn: number; psn: number; atMs: number }>()
589
+ // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
590
+ #packetEpochs = new Map<number, number>()
591
+
592
+ // Framerate detection state
593
+ #fpsDetected = false
594
+ #fecFps?: number
595
+ #fecInterleaveDepthMs = 0
596
+
597
+ // Worker error log rate-limiter — bounds console.warn output and exported
598
+ // error cardinality when the FEC Worker emits the same failure repeatedly
599
+ // with volatile packet details (e.g. ssStart) in the message text.
600
+ // Stable Worker codes aggregate those messages; uncoded/legacy messages are
601
+ // capped into an `other` bucket. This also covers wasm-bindgen
602
+ // "recursive use of an object" bubbled from add_source/add_repair during
603
+ // overlapping message processing). Without this, Point 5 of the 7-point
604
+ // validation harness — which caps headless warnings at 500 — fails even
605
+ // though the errors are duplicates of a single underlying event.
606
+ #workerErrorCounts = new Map<string, number>()
607
+ #decoderUnavailableEvents = 0
608
+ #repairSymbolSizeMismatchCount = 0
609
+
610
+ // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
611
+ // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
612
+ // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
613
+ // arrives via onBlockRecovered callback.
614
+ onBlockStarted:
615
+ | ((sbn: number, packetId: number, catalogTrackName?: string) => void)
616
+ | null = null
617
+ onBlockComplete:
618
+ | ((sbn: number, packetId: number, catalogTrackName?: string) => void)
619
+ | null = null
620
+ /** A block reached its fail bound. `blockClass` is its class at failure. */
621
+ onBlockFailed:
622
+ | ((
623
+ sbn: number,
624
+ packetId: number,
625
+ catalogTrackName: string | undefined,
626
+ blockClass: BlockClass,
627
+ ) => void)
628
+ | null = null
629
+ /**
630
+ * Fired once per stream when its Worker decoder stops being routable.
631
+ * `reason` is 'cleared' when clearFecWorker() removed it and 'disposed' when
632
+ * a symbol or reset found the registered client already disposed and
633
+ * evicted it. `fallbackDecoder` is 'sync' when a synchronous WASM decoder
634
+ * registered for the same stream keeps decoding its symbols, and 'none'
635
+ * when nothing does. Only 'none' leaves the stream unprotected: the host
636
+ * must then register a decoder again or leave the stream, because counting
637
+ * its symbols as handled would hide the loss.
638
+ */
639
+ onDecoderUnavailable: ((event: FecDecoderUnavailableEvent) => void) | null = null
640
+
641
+ // D-28 on-demand repair callbacks. When onRepairNeeded is registered, each
642
+ // block arms a one-shot repair deadline after the derived K-symbol source
643
+ // horizon; a block still short of K when it fires requests a per-SBN MoQ
644
+ // repair fetch upstream. The inactivity fail bound is unchanged either way —
645
+ // repair and failure are orthogonal timers, so wiring D-28 never delays
646
+ // failure accounting. onRepairResolved fires when a repair-requested block
647
+ // leaves the active set, with the outcome ("completed" after clean completion
648
+ // or recovery, "failed" at the fail bound) so the upstream in-flight slot
649
+ // (MulticastManager.clearRepairForBlock) can be released and logged.
650
+ onRepairNeeded:
651
+ | ((
652
+ sbn: number,
653
+ packetId: number,
654
+ catalogTrackName: string | undefined,
655
+ blockClass: BlockClass,
656
+ ) => void)
657
+ | null = null
658
+ onRepairResolved:
659
+ | ((
660
+ sbn: number,
661
+ packetId: number,
662
+ outcome: 'completed' | 'failed',
663
+ catalogTrackName: string | undefined,
664
+ via: RepairVia | null,
665
+ ) => void)
666
+ | null = null
667
+
668
+ /**
669
+ * A block that could not complete from its first-arrival source symbols
670
+ * alone was completed anyway: by FEC decode (in-band or QUIC repair
671
+ * symbols) or, after a D-28 request, by late symbols. Fired once per block.
672
+ */
673
+ onBlockRepaired:
674
+ | ((
675
+ sbn: number,
676
+ packetId: number,
677
+ catalogTrackName: string | undefined,
678
+ blockClass: BlockClass,
679
+ via: RepairVia,
680
+ ) => void)
681
+ | null = null
682
+ /** A block's class changed on new evidence or when classification was disabled. */
683
+ onBlockReclassified:
684
+ | ((
685
+ sbn: number,
686
+ packetId: number,
687
+ catalogTrackName: string | undefined,
688
+ from: BlockClass,
689
+ to: BlockClass,
690
+ evidence: ReclassificationEvidence,
691
+ ) => void)
692
+ | null = null
693
+ /** A video stream's classifier mode was established or changed. */
694
+ onClassifierMode:
695
+ | ((
696
+ packetId: number,
697
+ catalogTrackName: string | undefined,
698
+ mode: ClassifierMode,
699
+ reason: ClassifierReason | null,
700
+ ) => void)
701
+ | null = null
702
+ /** A block every symbol of which vanished was created by SBN evidence. */
703
+ onBlockVanished:
704
+ | ((sbn: number, packetId: number, catalogTrackName: string | undefined) => void)
705
+ | null = null
706
+ /** A block reached a terminal state (completed, recovered, or failed). */
707
+ onBlockResolved:
708
+ | ((sbn: number, packetId: number, catalogTrackName: string | undefined) => void)
709
+ | null = null
710
+ /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
711
+ onSourceDiscontinuity:
712
+ | ((packetId: number, catalogTrackName: string | undefined) => void)
713
+ | null = null
714
+
715
+ // Worker-path callbacks — async recovery and stats from FecWorkerClient.
716
+ onBlockRecovered: ((sbn: number, packetId: number, data: ArrayBuffer, meta: FrameMeta, catalogTrackName?: string) => void) | null = null
717
+ onFecStatsUpdate: ((packetId: number, stats: FecTrackStats) => void) | null = null
718
+
719
+ #encodeTrackName(catalogTrackName: string): string {
720
+ let encoded = this.#encodedTrackNames.get(catalogTrackName)
721
+ if (encoded === undefined) {
722
+ encoded = encodeURIComponent(catalogTrackName)
723
+ this.#encodedTrackNames.set(catalogTrackName, encoded)
724
+ }
725
+ return encoded
726
+ }
727
+
728
+ #streamKey(packetId: number, catalogTrackName?: string): string {
729
+ if (
730
+ packetId === this.#lastStreamKeyPacketId &&
731
+ catalogTrackName === this.#lastStreamKeyTrackName
732
+ ) {
733
+ return this.#lastStreamKey
734
+ }
735
+ const key = catalogTrackName === undefined
736
+ ? `${packetId}`
737
+ : `${packetId}:${this.#encodeTrackName(catalogTrackName)}`
738
+ this.#lastStreamKeyPacketId = packetId
739
+ this.#lastStreamKeyTrackName = catalogTrackName
740
+ this.#lastStreamKey = key
741
+ return key
742
+ }
743
+
744
+ #belongsToPacket(key: string, packetId: number): boolean {
745
+ return Number(key.split(':', 1)[0]) === packetId
746
+ }
747
+
748
+ #belongsToStream(key: string, packetId: number, catalogTrackName: string): boolean {
749
+ if (!this.#belongsToPacket(key, packetId)) return false
750
+ const parts = key.split(':')
751
+ const encodedTrackName = this.#encodeTrackName(catalogTrackName)
752
+ if (parts.length === 2) return parts[1] === encodedTrackName
753
+ if (parts.length >= 3) return parts[2] === encodedTrackName
754
+ return false
755
+ }
756
+
757
+ #packetIdsForStreamKeys(keys: Set<string>): number[] {
758
+ return [...new Set([...keys].map((key) => Number(key.split(':', 1)[0])))]
759
+ }
760
+
761
+ #parseStreamKey(key: string): { packetId: number; catalogTrackName?: string } {
762
+ const separator = key.indexOf(':')
763
+ if (separator < 0) return { packetId: Number(key) || 0 }
764
+ return {
765
+ packetId: Number(key.slice(0, separator)) || 0,
766
+ catalogTrackName: decodeURIComponent(key.slice(separator + 1)),
767
+ }
768
+ }
769
+
770
+ #blockKey(sbn: number, packetId: number, catalogTrackName?: string): string {
771
+ if (
772
+ sbn === this.#lastBlockKeySbn &&
773
+ packetId === this.#lastBlockKeyPacketId &&
774
+ catalogTrackName === this.#lastBlockKeyTrackName
775
+ ) {
776
+ return this.#lastBlockKey
777
+ }
778
+ const base = `${packetId}:${sbn}`
779
+ const key = catalogTrackName === undefined
780
+ ? base
781
+ : `${base}:${this.#encodeTrackName(catalogTrackName)}`
782
+ this.#lastBlockKeySbn = sbn
783
+ this.#lastBlockKeyPacketId = packetId
784
+ this.#lastBlockKeyTrackName = catalogTrackName
785
+ this.#lastBlockKey = key
786
+ return key
787
+ }
788
+
789
+ /** Record that `key` (block `sbn` on `packetId`) is held by a lookup set. */
790
+ #indexBlockKey(key: string, sbn: number, packetId: number): void {
791
+ let keys = this.#blockKeysBySbn.get(sbn)
792
+ if (!keys) {
793
+ keys = new Map()
794
+ this.#blockKeysBySbn.set(sbn, keys)
795
+ }
796
+ keys.set(key, packetId)
797
+ }
798
+
799
+ /** True while any set a catalog-name-less lookup consults still holds `key`. */
800
+ #isBlockKeyHeld(key: string): boolean {
801
+ return this.#activeBlocks.has(key) ||
802
+ this.#blockSourceCounts.has(key) ||
803
+ this.#blockCatalogTrackNames.has(key) ||
804
+ this.#completedBlocks.has(key)
805
+ }
806
+
807
+ /** Drop `key` from the SBN index once no lookup set holds it any more. */
808
+ #unindexBlockKey(key: string): void {
809
+ if (this.#isBlockKeyHeld(key)) return
810
+ const sbn = this.#parseBlockKey(key).sbn
811
+ const keys = this.#blockKeysBySbn.get(sbn)
812
+ if (!keys) return
813
+ keys.delete(key)
814
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn)
815
+ }
816
+
817
+ /**
818
+ * Make `key` terminal: late symbols for it are duplicates from now on. The
819
+ * key is retired terminalRetentionMsForPacket later, when no copy of any of
820
+ * its symbols can still be in flight on either transport and no frame can
821
+ * still be held behind it. Retirement is swept lazily here, on the stream's
822
+ * own terminal events, so it needs no timer.
823
+ */
824
+ #markTerminal(key: string, sbn: number, packetId: number, clean: boolean): void {
825
+ const nowMs = performance.now()
826
+ this.#retireTerminalBlocks(packetId, nowMs)
827
+ this.#forgetOrderedPending(key)
828
+ this.#completedBlocks.add(key)
829
+ if (clean) this.#cleanlyCompletedBlocks.add(key)
830
+ this.#indexBlockKey(key, sbn, packetId)
831
+ const expiresAtMs = nowMs + this.terminalRetentionMsForPacket(packetId)
832
+ this.#terminalExpiryMs.set(key, expiresAtMs)
833
+ let queue = this.#terminalQueues.get(packetId)
834
+ if (!queue) {
835
+ queue = new TerminalQueue()
836
+ this.#terminalQueues.set(packetId, queue)
837
+ }
838
+ queue.push({ key, expiresAtMs })
839
+ }
840
+
841
+ #retireTerminalBlocks(packetId: number, nowMs: number): void {
842
+ const queue = this.#terminalQueues.get(packetId)
843
+ if (!queue) return
844
+ for (let record = queue.peek(); record !== undefined; record = queue.peek()) {
845
+ if (record.expiresAtMs > nowMs) return
846
+ // A key made terminal again later (or reset and reused) owns a newer
847
+ // record; this one no longer describes it.
848
+ const current = this.#terminalExpiryMs.get(record.key) === record.expiresAtMs
849
+ // An ordered relay can still hand over the rest of a terminal block's
850
+ // symbols (a clean block's remaining repair symbols) for as long as the
851
+ // relay pauses. Until the stream passes the block's interleave horizon
852
+ // those symbols are late copies, not a new block, so the key stays.
853
+ if (current && this.#withinOrderedHorizon(record.key)) return
854
+ queue.shift()
855
+ if (!current) continue
856
+ this.#terminalExpiryMs.delete(record.key)
857
+ this.#completedBlocks.delete(record.key)
858
+ this.#cleanlyCompletedBlocks.delete(record.key)
859
+ this.#workerRecoveredBlocks.delete(record.key)
860
+ // The policy's terminal ledgers describe the same terminal state and
861
+ // retire with it: a failed block must never outlive its failure record
862
+ // as 'complete' (that would hide a loss from the release gate).
863
+ this.#failedBlocks.delete(record.key)
864
+ this.#resolvedBlockClasses.delete(record.key)
865
+ this.#repairedBlocks.delete(record.key)
866
+ this.#unindexBlockKey(record.key)
867
+ }
868
+ }
869
+
870
+ // -----------------------------------------------------------------------
871
+ // Ordered-relay settlement (MulticastSymbolDelivery 'ordered-relay')
872
+ // -----------------------------------------------------------------------
873
+
874
+ /**
875
+ * The decoder's interleave horizon for one stream, in blocks: the same
876
+ * retention the Worker and the WASM decoder are configured with, because it
877
+ * comes from the same function they do (`deriveFecRetentionBlocks`, over the
878
+ * block's delivery window and its span). The decoder retires every block
879
+ * more than this many blocks behind the newest SS_Start it saw, counted
880
+ * from below by `isoBlocksBehindLowerBound` (`cleanup_by_ss_start`), so
881
+ * settling earlier than this would decide a block the decoder would still
882
+ * have recovered.
883
+ *
884
+ * This used to call `deriveFecInterleaveDepth`, which returns D -- MEDIA
885
+ * UNITS per block, not a block count -- and a comment here asserted the two
886
+ * matched. They did, only while the decoder's retention was also (wrongly)
887
+ * sized in D. Once BLO-35597 sized retention as a real block count this
888
+ * settled 2-5 blocks early on the live ISS catalog at reorderToleranceMs=100
889
+ * (720p 1 vs 6, audio 2 vs 5), making the manager the binding constraint and
890
+ * the decoder fix inert on ordered relays. Both sides now consume one
891
+ * derivation; do not re-derive a horizon at either call site.
892
+ */
893
+ #orderedHorizonBlocksFor(packetId: number, config: ResolvedFECTrackConfig): number {
894
+ if (!FECManager.#hasOrderedGeometry(config)) {
895
+ throw new Error(
896
+ `[FECManager] packetId=${packetId}: ordered-relay settlement derives the ` +
897
+ `decoder's interleave horizon from the catalog interleaveDepthMs ` +
898
+ `(>= ${MIN_INTERLEAVE_DEPTH_MS}ms), the media-unit rate and the block ` +
899
+ `delivery window; got interleaveDepthMs=${config.interleaveDepthMs} ` +
900
+ `fps=${String(config.fps)} timeoutMs=${config.timeoutMs}.`,
901
+ )
902
+ }
903
+ // Config time is where failing closed is right, so a > 255 geometry throws
904
+ // from here with the message oti.ts wrote: it names interleaveDepthMs and
905
+ // the catalog fix. #derivableOrderedHorizon deliberately does not.
906
+ return deriveFecRetentionBlocks(config.timeoutMs, config.interleaveDepthMs)
907
+ }
908
+
909
+ /**
910
+ * Whether a stream's geometry can define an ordered-relay horizon at all.
911
+ * One definition, shared by the config-time and packet-feed callers, so the
912
+ * two can never disagree about which streams settle by stream order.
913
+ */
914
+ static #hasOrderedGeometry(config: ResolvedFECTrackConfig): boolean {
915
+ return (
916
+ config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS &&
917
+ // `fps` is no longer an input to the horizon, but it still gates WHICH
918
+ // streams settle by stream order at all: a track with no usable
919
+ // media-unit rate fell back to datagram semantics before this and must
920
+ // keep doing so. Removing this widens ordered-relay settlement to streams
921
+ // that never had it. Load-bearing — do not drop it as unused.
922
+ config.fps !== undefined &&
923
+ Number.isFinite(config.fps) &&
924
+ config.fps > 0 &&
925
+ Number.isFinite(config.timeoutMs) &&
926
+ config.timeoutMs > 0
927
+ )
928
+ }
929
+
930
+ /**
931
+ * The horizon for one stream, or undefined when its geometry cannot define
932
+ * one.
933
+ *
934
+ * `config.timeoutMs` is the block's delivery window. On the live path
935
+ * multicast-manager computes it with `jitterBufferMs: fec.reorderToleranceMs`
936
+ * and passes it to configure(), which is the same `deliveryWindowMs`
937
+ * fec-worker-setup sizes decoder retention from, so the two horizons are
938
+ * equal there.
939
+ *
940
+ * They are NOT equal on the fallback path, and the skew runs in the
941
+ * direction this file's invariant calls unsafe. `jitterBufferMs` reaches
942
+ * fec-manager only inside an explicit configure({timeoutMs}); all four of
943
+ * its own computeFecDeliveryWindowMs calls (one in #computeTimeout, one in
944
+ * configure(), two in setFramerate) omit it, so a manager-derived
945
+ * timeoutMs is tolerance-free and yields a
946
+ * horizon NARROWER than the decoder's retention — the direction that settles
947
+ * a block the decoder would still have recovered. At 720p/33ms the decoder
948
+ * retains ceil(133/33)+1 = 6 while a tolerance-free 33ms window gives
949
+ * ceil(33/33)+1 = 2. Two writes can also raise a validated timeoutMs
950
+ * afterwards without re-validating (configure()'s widening loop and
951
+ * setFramerate).
952
+ *
953
+ * Not fixed here: the real fix is to thread the tolerance into those four
954
+ * calls so both sides derive from the same quantity, which is a change to
955
+ * inputs fec-manager does not currently receive. Tracked in BLO-38250. The
956
+ * live ISS path does not hit it — multicast-manager always supplies both
957
+ * `timeoutMs` and `fps`, and setFramerate skips tracks that already carry
958
+ * `fps` — so this is a latent skew on the fallback, not a live defect. Do
959
+ * not read the old "can only skew narrower, never wider" note as a safety
960
+ * argument: narrower IS the failing direction.
961
+ */
962
+ #derivableOrderedHorizon(config: ResolvedFECTrackConfig, packetId: number): number | undefined {
963
+ if (!FECManager.#hasOrderedGeometry(config)) return undefined
964
+ try {
965
+ // `tryDeriveFecRetentionBlocks`, not the throwing variant: this is the
966
+ // per-symbol path (#settlesByOrder -> #orderedHorizonBlocks, from
967
+ // noteBlockActivity on every source and repair symbol), and a geometry
968
+ // past the 255-block ceiling is STEADY STATE, not a transient --
969
+ // `timeoutMs` does not narrow back on its own. Throwing here would
970
+ // construct an Error and capture a stack in oti.ts, then unwind it,
971
+ // for every symbol on the stream, and #advanceOrderedFrontier's
972
+ // `blocks === undefined` branch re-enters noteBlockActivity per pending
973
+ // SBN and would multiply it again. The ceiling itself stays owned by
974
+ // oti.ts -- open-coding the comparison here would re-create the second
975
+ // derivation this change exists to remove.
976
+ const blocks = tryDeriveFecRetentionBlocks(config.timeoutMs, config.interleaveDepthMs)
977
+ if (blocks === undefined) {
978
+ // Falls back to datagram semantics through the `blocks === undefined`
979
+ // branch already written for it in #advanceOrderedFrontier. Two writes
980
+ // can raise a track's timeoutMs after #orderedHorizonBlocksFor
981
+ // validated it (configure()'s widening loop and setFramerate's), and
982
+ // neither re-validates, so this is reachable without a second
983
+ // config-time check.
984
+ this.#noteLeftOrderedSettlement(
985
+ packetId,
986
+ `geometry cannot define a retention horizon within the 255-block ceiling ` +
987
+ `(timeoutMs=${config.timeoutMs}ms over interleaveDepthMs=${config.interleaveDepthMs}ms)`,
988
+ )
989
+ }
990
+ return blocks
991
+ } catch (error) {
992
+ // Backstop only -- nothing above throws today. Deliberately unnarrowed:
993
+ // if the callee grows a new throw, this is what makes it visible rather
994
+ // than silently swallowed. The contract of this path
995
+ // (#orderedHorizonBlocks) is that it must not throw.
996
+ this.#noteLeftOrderedSettlement(packetId, String(error))
997
+ return undefined
998
+ }
999
+ }
1000
+
1001
+ /**
1002
+ * Warn once per stream that it dropped from ordered-relay settlement to the
1003
+ * datagram deadline. Swallowing is right for the packet-feed contract, but a
1004
+ * configured stream changing settlement mid-flight is a behavioural change,
1005
+ * and it is otherwise indistinguishable from a stream that never had
1006
+ * geometry.
1007
+ */
1008
+ #noteLeftOrderedSettlement(packetId: number, reason: string): void {
1009
+ if (this.#orderedHorizonWarnedFor.has(packetId)) return
1010
+ this.#orderedHorizonWarnedFor.add(packetId)
1011
+ console.warn(
1012
+ `[FECManager] packetId=${packetId} left ordered-relay settlement for the datagram deadline: ${reason}`,
1013
+ )
1014
+ }
1015
+
1016
+ /**
1017
+ * The stream's interleave horizon, or undefined when its geometry cannot
1018
+ * define one. Two different streams reach that case, with different causes:
1019
+ * a packetId that was never configured, and so resolves to the manager
1020
+ * defaults (explicitly configured tracks are refused an underivable geometry
1021
+ * at config time — #upsertTrackConfig, setMulticastSymbolDelivery); or a
1022
+ * configured track whose timeoutMs was later widened past the 255-block
1023
+ * ceiling without re-validating, which #derivableOrderedHorizon catches
1024
+ * rather than throwing from the packet-feed path. Either way the stream
1025
+ * keeps datagram semantics instead of throwing. The manager defaults can
1026
+ * also change under a stream that already holds blocks, so a caller cannot
1027
+ * assume a horizon that was defined when a block was held is still defined
1028
+ * (see #advanceOrderedFrontier).
1029
+ */
1030
+ #orderedHorizonBlocks(packetId: number): number | undefined {
1031
+ return this.#derivableOrderedHorizon(this.#resolveTrackConfig(packetId), packetId)
1032
+ }
1033
+
1034
+ /** True while a block of an ordered-relay stream can still receive symbols. */
1035
+ #withinOrderedHorizon(key: string): boolean {
1036
+ if (this.#multicastSymbolDelivery !== 'ordered-relay') return false
1037
+ const block = this.#parseBlockKey(key)
1038
+ const frontier = this.#orderedFrontiers.get(
1039
+ this.#streamKey(block.packetId, block.catalogTrackName),
1040
+ )
1041
+ if (frontier === undefined) return false
1042
+ const horizon = this.#orderedHorizonBlocks(block.packetId)
1043
+ if (horizon === undefined) return false
1044
+ return this.#blocksBehind(block.sbn, frontier, block.packetId) <= horizon
1045
+ }
1046
+
1047
+ /** Whether a block's fate is decided by stream order rather than a timer. */
1048
+ #settlesByOrder(key: string): boolean {
1049
+ return this.#multicastSymbolDelivery === 'ordered-relay' &&
1050
+ (this.#blockPathCounts.get(key)?.multicastSymbols ?? 0) > 0 &&
1051
+ this.#orderedHorizonBlocks(this.#parseBlockKey(key).packetId) !== undefined
1052
+ }
1053
+
1054
+ #forgetOrderedPending(key: string): void {
1055
+ if (this.#orderedPendingBlocks.size === 0) return
1056
+ const block = this.#parseBlockKey(key)
1057
+ const streamKey = this.#streamKey(block.packetId, block.catalogTrackName)
1058
+ const pending = this.#orderedPendingBlocks.get(streamKey)
1059
+ if (pending?.get(block.sbn) !== key) return
1060
+ pending.delete(block.sbn)
1061
+ if (pending.size === 0) this.#orderedPendingBlocks.delete(streamKey)
1062
+ }
1063
+
1064
+ /**
1065
+ * Record the stream position of a multicast symbol and settle every pending
1066
+ * block it proves final: a block more than the interleave horizon behind the
1067
+ * frontier has already been handed every symbol the relay will deliver.
1068
+ */
1069
+ #advanceOrderedFrontier(
1070
+ streamKey: string,
1071
+ sbn: number,
1072
+ packetId: number,
1073
+ catalogTrackName?: string,
1074
+ ): void {
1075
+ const previous = this.#orderedFrontiers.get(streamKey)
1076
+ const frontier = previous === undefined || this.#blockPrecedes(previous, sbn)
1077
+ ? sbn
1078
+ : previous
1079
+ if (frontier !== previous) this.#orderedFrontiers.set(streamKey, frontier)
1080
+ const pending = this.#orderedPendingBlocks.get(streamKey)
1081
+ if (!pending) return
1082
+ const blocks = this.#orderedHorizonBlocks(packetId)
1083
+ if (blocks === undefined) {
1084
+ // A configured stream whose timeoutMs was widened past the 255-block
1085
+ // ceiling after validation (#derivableOrderedHorizon); an unconfigured
1086
+ // one never gets here (feedSymbolFromSource refuses it). Stream
1087
+ // order can no longer settle its held blocks, so hand them to the
1088
+ // datagram deadline -- as setMulticastSymbolDelivery('datagram') does --
1089
+ // rather than settle them a horizon early or hold them with no timer.
1090
+ this.#orderedPendingBlocks.delete(streamKey)
1091
+ for (const pendingSbn of pending.keys()) {
1092
+ this.noteBlockActivity(pendingSbn, packetId, catalogTrackName)
1093
+ }
1094
+ return
1095
+ }
1096
+ for (const [pendingSbn, key] of pending) {
1097
+ if (this.#blocksBehind(pendingSbn, frontier, packetId) <= blocks) continue
1098
+ pending.delete(pendingSbn)
1099
+ this.#settleOrderedBlock(key, pendingSbn, packetId, catalogTrackName)
1100
+ }
1101
+ if (pending.size === 0 && this.#orderedPendingBlocks.get(streamKey) === pending) {
1102
+ this.#orderedPendingBlocks.delete(streamKey)
1103
+ }
1104
+ }
1105
+
1106
+ /**
1107
+ * Decide a block the ordered relay has finished delivering. Its accounting
1108
+ * is final: SSB_length (from any repair symbol) against the source and
1109
+ * repair symbols it holds says whether the decoder can still recover it.
1110
+ * A block short of that asks for repair when D-28 is wired, under the same
1111
+ * post-request fetch budget the datagram path grants; otherwise, and for a
1112
+ * block the decoder holds enough symbols for, the decoder finalizes it
1113
+ * exactly as a datagram deadline would (a Worker acknowledges the cleanup
1114
+ * only after every earlier symbol, so an in-flight recovery still wins).
1115
+ */
1116
+ #settleOrderedBlock(
1117
+ key: string,
1118
+ sbn: number,
1119
+ packetId: number,
1120
+ catalogTrackName?: string,
1121
+ ): void {
1122
+ if (
1123
+ this.#completedBlocks.has(key) ||
1124
+ this.#pendingWorkerCleanups.has(key) ||
1125
+ this.#repairRequestedBlocks.has(key)
1126
+ ) return
1127
+ const authoredLength = this.#blockAuthoredLengths.get(key)
1128
+ const received =
1129
+ (this.#blockSourceCounts.get(key) ?? 0) +
1130
+ (this.#blockRepairRsIds.get(key)?.size ?? 0)
1131
+ if (
1132
+ this.onRepairNeeded &&
1133
+ (authoredLength === undefined || received < authoredLength)
1134
+ ) {
1135
+ this.#requestRepair(sbn, packetId, catalogTrackName, true)
1136
+ return
1137
+ }
1138
+ this.#traceLifecycle('horizon-settled', sbn, packetId, catalogTrackName)
1139
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName)
1140
+ }
1141
+
1142
+ /** Register a block whose multicast symbols arrive over an ordered relay. */
1143
+ #holdForOrderedSettlement(
1144
+ key: string,
1145
+ sbn: number,
1146
+ packetId: number,
1147
+ catalogTrackName?: string,
1148
+ ): void {
1149
+ // A block that started on the other transport may already hold a timer.
1150
+ // Its multicast symbols now decide it by order; a wall clock cannot.
1151
+ this.#clearRepairDeadline(key)
1152
+ if (this.#activeBlocks.has(key)) {
1153
+ this.#clearBlockTimer(key)
1154
+ this.#unindexBlockKey(key)
1155
+ }
1156
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
1157
+ let pending = this.#orderedPendingBlocks.get(streamKey)
1158
+ if (!pending) {
1159
+ pending = new Map()
1160
+ this.#orderedPendingBlocks.set(streamKey, pending)
1161
+ }
1162
+ pending.set(sbn, key)
1163
+ }
1164
+
1165
+ /** Cancel and forget a block's inactivity timer and deadline. */
1166
+ #clearBlockTimer(key: string): void {
1167
+ const timer = this.#activeBlocks.get(key)
1168
+ if (timer?.handle != null) clearTimeout(timer.handle)
1169
+ this.#activeBlocks.delete(key)
1170
+ this.#activeBlockDeadlinesMs.delete(key)
1171
+ this.#blockWaitDeadlinesMs.delete(key)
1172
+ this.#repairHoldUntilMs.delete(key)
1173
+ }
1174
+
1175
+ #parseBlockKey(key: string): { packetId: number; sbn: number; catalogTrackName?: string } {
1176
+ const [packetIdText, sbnText, ...catalogParts] = key.split(':')
1177
+ const catalogTrackName = catalogParts.length > 0
1178
+ ? decodeURIComponent(catalogParts.join(':'))
1179
+ : undefined
1180
+ return {
1181
+ packetId: Number(packetIdText) || 0,
1182
+ sbn: Number(sbnText) || 0,
1183
+ ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
1184
+ }
1185
+ }
1186
+
1187
+ #decoderForPacket(packetId: number, catalogTrackName?: string) {
1188
+ return this.#fecDecoders.get(this.#streamKey(packetId, catalogTrackName))
1189
+ ?? this.#fecDecoders.get(this.#streamKey(packetId))
1190
+ }
1191
+
1192
+ #workerForPacket(packetId: number, catalogTrackName?: string) {
1193
+ return this.#workerClients.get(this.#streamKey(packetId, catalogTrackName))
1194
+ ?? this.#workerClients.get(this.#streamKey(packetId))
1195
+ }
1196
+
1197
+ /**
1198
+ * The stream's Worker client for routing, or undefined after evicting a
1199
+ * registered client that was already disposed. A disposed client throws on
1200
+ * every command, so it leaves routing here before a symbol reaches it and
1201
+ * the stream reports its decoder unavailable instead.
1202
+ */
1203
+ #routableWorkerForPacket(packetId: number, catalogTrackName?: string): FecWorkerClient | undefined {
1204
+ const client = this.#workerForPacket(packetId, catalogTrackName)
1205
+ if (client === undefined || client.disposed !== true) return client
1206
+ this.#evictDisposedWorker(client)
1207
+ return undefined
1208
+ }
1209
+
1210
+ #claimDecoderBlock(
1211
+ client: object,
1212
+ sbn: number,
1213
+ catalogTrackName?: string,
1214
+ ): boolean {
1215
+ let blocks = this.#decoderBlockOwners.get(client)
1216
+ if (!blocks) {
1217
+ blocks = new Map()
1218
+ this.#decoderBlockOwners.set(client, blocks)
1219
+ }
1220
+ const owner = blocks.get(sbn)
1221
+ if (!owner) {
1222
+ blocks.set(sbn, { catalogTrackName, conflicted: false })
1223
+ if (blocks.size > 512) {
1224
+ const stale = [...blocks.keys()].slice(0, 256)
1225
+ for (const key of stale) blocks.delete(key)
1226
+ }
1227
+ return true
1228
+ }
1229
+ if (owner.conflicted) return false
1230
+ if (owner.catalogTrackName === catalogTrackName) return true
1231
+ owner.conflicted = true
1232
+ return false
1233
+ }
1234
+
1235
+ #decoderBlockCatalogTrackName(client: object, sbn: number): string | undefined {
1236
+ const owner = this.#decoderBlockOwners.get(client)?.get(sbn)
1237
+ return owner?.conflicted ? undefined : owner?.catalogTrackName
1238
+ }
1239
+
1240
+ #resetDecoderBlockOwners(client: object, catalogTrackName: string): void {
1241
+ const blocks = this.#decoderBlockOwners.get(client)
1242
+ if (!blocks) return
1243
+ for (const [sbn, owner] of blocks) {
1244
+ if (owner.catalogTrackName === catalogTrackName || owner.conflicted) {
1245
+ blocks.delete(sbn)
1246
+ }
1247
+ }
1248
+ if (blocks.size === 0) this.#decoderBlockOwners.delete(client)
1249
+ }
1250
+
1251
+ #discardFecDecoderClient(client: WasmFecDecoder): void {
1252
+ for (const [key, entry] of this.#fecDecoders) {
1253
+ if (entry.client === client) this.#fecDecoders.delete(key)
1254
+ }
1255
+ this.#decoderBlockOwners.delete(client)
1256
+ }
1257
+
1258
+ #assertExclusiveDecoderClient(
1259
+ streamKey: string,
1260
+ client: object,
1261
+ registrations: Iterable<readonly [string, object]>,
1262
+ kind: 'decoder' | 'worker',
1263
+ ): void {
1264
+ for (const [registeredKey, registeredClient] of registrations) {
1265
+ if (registeredClient !== client || registeredKey === streamKey) continue
1266
+ throw new Error(
1267
+ `[FECManager] ${kind} client is already registered for stream ${registeredKey}; ` +
1268
+ `create one client per physical stream`,
1269
+ )
1270
+ }
1271
+ }
1272
+
1273
+ #statsForPacket(packetId: number): MutableFecCounters {
1274
+ let stats = this.#fecTrackStats.get(packetId)
1275
+ if (!stats) {
1276
+ stats = newFecCounters()
1277
+ this.#fecTrackStats.set(packetId, stats)
1278
+ }
1279
+ return stats
1280
+ }
1281
+
1282
+ #markPathBlockComplete(sbn: number, packetId: number, catalogTrackName?: string): void {
1283
+ const block = this.#blockPathCounts.get(this.#blockKey(sbn, packetId, catalogTrackName))
1284
+ if (block) block.complete = true
1285
+ }
1286
+
1287
+ /** Cancel and forget a block's D-28 repair-deadline timer. */
1288
+ #clearRepairDeadline(key: string): void {
1289
+ const timer = this.#repairDeadlines.get(key)
1290
+ if (timer?.handle != null) clearTimeout(timer.handle)
1291
+ this.#repairDeadlines.delete(key)
1292
+ this.#repairDeadlineAtMs.delete(key)
1293
+ }
1294
+
1295
+ /**
1296
+ * Move a block's D-28 repair deadline to `delayMs` from now. The timer
1297
+ * already armed for an earlier moment fires first and re-arms for the
1298
+ * remainder, so repeated source progress costs no timer operation.
1299
+ */
1300
+ #armRepairDeadline(
1301
+ key: string,
1302
+ sbn: number,
1303
+ packetId: number,
1304
+ catalogTrackName: string | undefined,
1305
+ delayMs: number,
1306
+ ): void {
1307
+ const deadlineMs = performance.now() + delayMs
1308
+ this.#repairDeadlineAtMs.set(key, deadlineMs)
1309
+ const armed = this.#repairDeadlines.get(key)
1310
+ if (armed?.handle != null) {
1311
+ if (armed.fireAtMs <= deadlineMs) return
1312
+ clearTimeout(armed.handle)
1313
+ }
1314
+ const timer: DeadlineTimer = { handle: null, fireAtMs: deadlineMs }
1315
+ const onFire = (): void => {
1316
+ if (this.#repairDeadlines.get(key) !== timer) return
1317
+ const currentDeadlineMs = this.#repairDeadlineAtMs.get(key)
1318
+ const nowMs = performance.now()
1319
+ if (currentDeadlineMs !== undefined && currentDeadlineMs > nowMs) {
1320
+ timer.fireAtMs = currentDeadlineMs
1321
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - nowMs))
1322
+ return
1323
+ }
1324
+ timer.handle = null
1325
+ this.#requestRepair(sbn, packetId, catalogTrackName)
1326
+ }
1327
+ timer.handle = setTimeout(onFire, delayMs)
1328
+ this.#repairDeadlines.set(key, timer)
1329
+ }
1330
+
1331
+ #requestRepair(
1332
+ sbn: number,
1333
+ packetId: number,
1334
+ catalogTrackName?: string,
1335
+ /**
1336
+ * Ordered-relay settlement only: the stream has proved the block final,
1337
+ * so its multicast wait ends now. A datagram block keeps the wait its
1338
+ * accepted symbols armed.
1339
+ */
1340
+ settledByOrder = false,
1341
+ ): void {
1342
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
1343
+ if (
1344
+ this.#completedBlocks.has(key) ||
1345
+ !this.onRepairNeeded ||
1346
+ this.#repairRequestedBlocks.has(key)
1347
+ ) return
1348
+
1349
+ const deadline = this.#repairDeadlines.get(key)
1350
+ if (deadline?.handle != null) clearTimeout(deadline.handle)
1351
+ this.#repairDeadlines.set(key, null)
1352
+ this.#repairDeadlineAtMs.delete(key)
1353
+ this.#repairRequestedBlocks.add(key)
1354
+
1355
+ // The request itself grants no time (BLO-35597). The multicast wait keeps
1356
+ // running, extended by any late symbol; the repair scheduler extends the
1357
+ // block past it (holdBlockForRepair) only for a FETCH it admits, i.e. one
1358
+ // the measured reliable-path RTT says can land before the block's
1359
+ // presentation deadline. A request it declines leaves the block on the
1360
+ // multicast wait alone, so no doomed FETCH is sent and none is aborted
1361
+ // for want of a grace that could never have covered the round trip.
1362
+ if (settledByOrder) this.#armBlockTimeout(sbn, packetId, catalogTrackName, 0)
1363
+ this.#traceLifecycle('repair-requested', sbn, packetId, catalogTrackName)
1364
+ this.onRepairNeeded(
1365
+ sbn,
1366
+ packetId,
1367
+ catalogTrackName,
1368
+ this.blockClassFor(sbn, packetId, catalogTrackName),
1369
+ )
1370
+ }
1371
+
1372
+ // ── Keyframe-protected repair policy ──
1373
+
1374
+ /**
1375
+ * The classifier geometry of one stream. A stream-scoped configuration
1376
+ * wins. Once any stream of a packetId was configured with its own geometry,
1377
+ * a sibling stream without one has none that provably belongs to it: the
1378
+ * packet-level geometry may be another rung's (a different framerate or
1379
+ * GOP), so it runs all-protected (`stream-geometry-absent`).
1380
+ */
1381
+ #geometryFor(packetId: number, catalogTrackName?: string): BlockClassifierGeometry {
1382
+ const own = this.#streamGeometries.get(this.#streamKey(packetId, catalogTrackName))
1383
+ if (own) return own
1384
+ const config = this.#trackConfigs.get(packetId)
1385
+ if (config?.trackKind === 'audio') return { trackKind: 'audio' }
1386
+ for (const key of this.#streamGeometries.keys()) {
1387
+ if (this.#belongsToPacket(key, packetId)) {
1388
+ return { trackKind: 'video', mode: 'all-protected', reason: 'stream-geometry-absent' }
1389
+ }
1390
+ }
1391
+ if (config?.geometry) return config.geometry
1392
+ // No catalog cadence reached this track: every video block is protected.
1393
+ return { trackKind: 'video', mode: 'all-protected', reason: 'keyframe-cadence-absent' }
1394
+ }
1395
+
1396
+ #classifierFor(packetId: number, catalogTrackName?: string): BlockClassifier {
1397
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
1398
+ let classifier = this.#classifiers.get(streamKey)
1399
+ if (!classifier) {
1400
+ classifier = new BlockClassifier(this.#geometryFor(packetId, catalogTrackName))
1401
+ this.#classifiers.set(streamKey, classifier)
1402
+ if (classifier.geometry.trackKind === 'video') {
1403
+ this.onClassifierMode?.(packetId, catalogTrackName, classifier.mode, classifier.reason)
1404
+ }
1405
+ }
1406
+ return classifier
1407
+ }
1408
+
1409
+ #applyClassifierChanges(
1410
+ packetId: number,
1411
+ catalogTrackName: string | undefined,
1412
+ changes: readonly ClassifierChange[],
1413
+ ): void {
1414
+ for (const change of changes) {
1415
+ if (change.kind === 'mode') {
1416
+ this.onClassifierMode?.(packetId, catalogTrackName, change.mode, change.reason)
1417
+ } else {
1418
+ this.onBlockReclassified?.(
1419
+ change.sbn,
1420
+ packetId,
1421
+ catalogTrackName,
1422
+ change.from,
1423
+ change.to,
1424
+ change.evidence,
1425
+ )
1426
+ }
1427
+ }
1428
+ }
1429
+
1430
+ /**
1431
+ * Freeze a block's class at resolution and drop its classifier state. The
1432
+ * frozen class answers every later query (a recovery counted after the
1433
+ * block was cancelled, a failure event) exactly.
1434
+ */
1435
+ #retireBlockClass(
1436
+ key: string,
1437
+ sbn: number,
1438
+ packetId: number,
1439
+ catalogTrackName?: string,
1440
+ ): BlockClass {
1441
+ const frozen = this.#resolvedBlockClasses.get(key)
1442
+ if (frozen !== undefined) return frozen
1443
+ const blockClass = this.#peekClass(sbn, packetId, catalogTrackName)
1444
+ this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.forget(sbn)
1445
+ this.#resolvedBlockClasses.set(key, blockClass)
1446
+ this.#materializedBlocks.delete(key)
1447
+ return blockClass
1448
+ }
1449
+
1450
+ /** A block's live class without creating classifier state for the stream. */
1451
+ #peekClass(sbn: number, packetId: number, catalogTrackName?: string): BlockClass {
1452
+ const classifier = this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))
1453
+ if (classifier) return classifier.classOf(sbn)
1454
+ return this.#geometryFor(packetId, catalogTrackName).trackKind === 'audio' ? 'audio' : 'unknown'
1455
+ }
1456
+
1457
+ #viaFor(key: string): RepairVia {
1458
+ return (this.#blockPathCounts.get(key)?.moqSymbols ?? 0) > 0 ? 'quic' : 'inband'
1459
+ }
1460
+
1461
+ #noteBlockRepaired(
1462
+ key: string,
1463
+ sbn: number,
1464
+ packetId: number,
1465
+ catalogTrackName?: string,
1466
+ ): void {
1467
+ if (this.#repairedBlocks.has(key)) return
1468
+ this.#repairedBlocks.add(key)
1469
+ this.onBlockRepaired?.(
1470
+ sbn,
1471
+ packetId,
1472
+ catalogTrackName,
1473
+ this.blockClassFor(sbn, packetId, catalogTrackName),
1474
+ this.#viaFor(key),
1475
+ )
1476
+ }
1477
+
1478
+ // Deliberately one block tighter than deriveFecRetentionBlocks over the same
1479
+ // inputs (that function's `+ 1`). Different question: the retention horizon
1480
+ // asks how long the decoder still ACCEPTS symbols for a block, this asks how
1481
+ // many blocks a stream can live behind (or ahead of) its frontier before a
1482
+ // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
1483
+ // The extra block of retention is slack for a block still being fed; a block
1484
+ // nothing has been heard from does not get it. Not the units defect — but it
1485
+ // is the next place the two can drift, so change both or neither.
1486
+ #liveWindowBlocks(config: ResolvedFECTrackConfig): number | null {
1487
+ if (config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS || config.timeoutMs <= 0) return null
1488
+ return Math.ceil(config.timeoutMs / config.interleaveDepthMs)
1489
+ }
1490
+
1491
+ /**
1492
+ * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
1493
+ * advance the stream's frontier, the newest block start seen.
1494
+ *
1495
+ * A SOURCE symbol whose block goes back further than one live window, or
1496
+ * jumps further than the stream could have produced since its last symbol,
1497
+ * is a source discontinuity, not loss. A repair symbol can only advance the
1498
+ * frontier: a D-28 fetch legitimately answers for an old block, so it never
1499
+ * signals a discontinuity.
1500
+ *
1501
+ * The producer closes a block at its Dth media-unit boundary OR when K
1502
+ * source symbols filled it, so one interleave span can start several blocks
1503
+ * (every large keyframe does). What bounds a forward jump is therefore
1504
+ * packet evidence, not a block rate: SS_ID advances by one per FEC source
1505
+ * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
1506
+ * per packet of the packet_id, so with both source symbols'
1507
+ * packet_sequence_number a block start can move at most the packets sent
1508
+ * between them plus the anchor's own offset into its block (< K). Without
1509
+ * it, only the D-close rate is known.
1510
+ *
1511
+ * Vanished blocks are not enumerated here: their starts are unknown until a
1512
+ * repair states them. The SS_IDs between two stated blocks become one
1513
+ * repair-less span when the later block's repair arrives (placeIsoRepair).
1514
+ */
1515
+ #noteSbnSeen(
1516
+ sbn: number,
1517
+ packetId: number,
1518
+ catalogTrackName: string | undefined,
1519
+ symbol: 'source' | 'repair',
1520
+ packetSequenceNumber?: number,
1521
+ ): void {
1522
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
1523
+ const now = performance.now()
1524
+ const previous = this.#highestSbn.get(streamKey)
1525
+ const anchor = this.#sourceAnchors.get(streamKey)
1526
+ const psn = symbol === 'source' &&
1527
+ packetSequenceNumber !== undefined &&
1528
+ Number.isSafeInteger(packetSequenceNumber) &&
1529
+ packetSequenceNumber >= 0 &&
1530
+ packetSequenceNumber <= 0xffff_ffff
1531
+ ? packetSequenceNumber
1532
+ : undefined
1533
+ const anchorHere = (): void => {
1534
+ if (psn !== undefined && (anchor === undefined || !this.#blockPrecedes(sbn, anchor.sbn))) {
1535
+ this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now })
1536
+ }
1537
+ }
1538
+ const discontinuity = (): void => {
1539
+ // The classifier compares authored order with SBN order only within
1540
+ // one continuous SBN sequence.
1541
+ this.#classifiers.get(streamKey)?.noteSourceDiscontinuity()
1542
+ this.#highestSbn.set(streamKey, { sbn, atMs: now })
1543
+ if (psn === undefined) this.#sourceAnchors.delete(streamKey)
1544
+ else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now })
1545
+ this.onSourceDiscontinuity?.(packetId, catalogTrackName)
1546
+ }
1547
+ if (previous === undefined) {
1548
+ this.#highestSbn.set(streamKey, { sbn, atMs: now })
1549
+ anchorHere()
1550
+ return
1551
+ }
1552
+ const config = this.#resolveTrackConfig(packetId)
1553
+ const window = this.#liveWindowBlocks(config)
1554
+ if (!this.#blockPrecedes(previous.sbn, sbn)) {
1555
+ if (symbol === 'source' && window !== null &&
1556
+ this.#blocksBehind(sbn, previous.sbn, packetId) > window) {
1557
+ discontinuity()
1558
+ return
1559
+ }
1560
+ anchorHere()
1561
+ return
1562
+ }
1563
+ const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1
1564
+ let plausible = true
1565
+ if (window !== null) {
1566
+ // A packet_sequence_number that did not advance says nothing (a
1567
+ // producer that does not maintain it); only then is the D-close rate
1568
+ // the whole bound.
1569
+ if (psn !== undefined && anchor !== undefined &&
1570
+ this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
1571
+ // A block start can move at most the packets sent since the anchor,
1572
+ // plus the anchor's own offset into its block (< K). Packets sent
1573
+ // from the anchor packet to this one, serial arithmetic (RFC 1982):
1574
+ // more than half the space means it went backwards.
1575
+ const sent = (psn - anchor.psn) >>> 0
1576
+ plausible =
1577
+ sent <= 0x7fff_ffff &&
1578
+ serial32Distance(anchor.sbn, sbn) <= sent + config.k
1579
+ } else {
1580
+ plausible = missing <= window + Math.ceil((now - previous.atMs) / config.interleaveDepthMs)
1581
+ }
1582
+ }
1583
+ if (!plausible) {
1584
+ if (symbol === 'repair') return
1585
+ discontinuity()
1586
+ return
1587
+ }
1588
+ this.#highestSbn.set(streamKey, { sbn, atMs: now })
1589
+ anchorHere()
1590
+ }
1591
+
1592
+ /*
1593
+ * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
1594
+ * SS_Start and SS_ID is a 32-bit serial number (ISO/IEC 23008-1 C.5.2), so
1595
+ * blocks are ordered by RFC 1982 comparison of their starts. Only configured
1596
+ * streams hold blocks: every entry point refuses an unconfigured packetId.
1597
+ */
1598
+ #blockPrecedes(a: number, b: number): boolean {
1599
+ return serial32Precedes(a, b)
1600
+ }
1601
+
1602
+ /**
1603
+ * Blocks `a` lies behind `b` (0 when it does not precede it). Blocks vary
1604
+ * in length (K' = SSB_length <= K), so only a lower bound is known: the one
1605
+ * metric the decoder and the worker retire by too.
1606
+ */
1607
+ #blocksBehind(a: number, b: number, packetId: number): number {
1608
+ return isoBlocksBehindLowerBound(a, b, this.kForPacket(packetId))
1609
+ }
1610
+
1611
+ #materializeBlock(
1612
+ sbn: number,
1613
+ packetId: number,
1614
+ catalogTrackName: string | undefined,
1615
+ repairable: boolean,
1616
+ ): void {
1617
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
1618
+ if (this.#blockResolutionFor(key) !== 'untracked') return
1619
+ this.#materializedBlocks.add(key)
1620
+ this.#classifierFor(packetId, catalogTrackName).touch(sbn)
1621
+ this.onBlockVanished?.(sbn, packetId, catalogTrackName)
1622
+ if (repairable) {
1623
+ this.noteBlockActivity(sbn, packetId, catalogTrackName, true)
1624
+ } else {
1625
+ this.#failBlock(sbn, packetId, catalogTrackName)
1626
+ }
1627
+ }
1628
+
1629
+ #blockResolutionFor(key: string): FecBlockResolution {
1630
+ if (this.#failedBlocks.has(key)) return 'failed'
1631
+ if (this.#completedBlocks.has(key)) return 'complete'
1632
+ if (
1633
+ this.#activeBlocks.has(key) ||
1634
+ this.#pendingWorkerCleanups.has(key) ||
1635
+ this.#repairDeadlines.has(key) ||
1636
+ this.#blockSourceCounts.has(key) ||
1637
+ this.#blockRepairRsIds.has(key) ||
1638
+ this.#materializedBlocks.has(key)
1639
+ ) {
1640
+ return 'pending'
1641
+ }
1642
+ return 'untracked'
1643
+ }
1644
+
1645
+ #bumpEpoch(packetId: number): void {
1646
+ this.#packetEpochs.set(packetId, (this.#packetEpochs.get(packetId) ?? 0) + 1)
1647
+ }
1648
+
1649
+ #traceLifecycle(
1650
+ event: FecLifecycleTrace['event'],
1651
+ sbn: number,
1652
+ packetId: number,
1653
+ catalogTrackName?: string,
1654
+ rsId?: number,
1655
+ ): void {
1656
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
1657
+ const deadline = this.#activeBlockDeadlinesMs.get(key)
1658
+ const decoderPath = this.#syncDecoderBlockOwners.has(key)
1659
+ ? 'sync'
1660
+ : this.#workerForPacket(packetId, catalogTrackName)
1661
+ ? 'worker'
1662
+ : this.#decoderForPacket(packetId, catalogTrackName)
1663
+ ? 'sync'
1664
+ : 'none'
1665
+ this.#lifecycleTrace.push({
1666
+ atMs: Date.now(),
1667
+ event,
1668
+ packetId,
1669
+ sbn,
1670
+ ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
1671
+ sourceCount: this.#blockSourceCounts.get(key) ?? 0,
1672
+ sourceEsis: [...(this.#blockSourceEsis.get(key) ?? [])].sort((a, b) => a - b),
1673
+ repairRsIds: [...(this.#blockRepairRsIds.get(key) ?? [])].sort((a, b) => a - b),
1674
+ decoderPath,
1675
+ ...(deadline === undefined
1676
+ ? {}
1677
+ : { deadlineRemainingMs: Math.max(0, deadline - performance.now()) }),
1678
+ pendingCleanup: this.#pendingWorkerCleanups.has(key),
1679
+ ...(rsId === undefined ? {} : { rsId }),
1680
+ })
1681
+ if (this.#lifecycleTrace.length > 64) this.#lifecycleTrace.splice(0, 32)
1682
+ }
1683
+
1684
+ #defaultTrackConfig(): ResolvedFECTrackConfig {
1685
+ return {
1686
+ k: this.#fecK,
1687
+ symbolSize: this.#fecSymbolSize,
1688
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
1689
+ fps: this.#fecFps,
1690
+ timeoutMs: this.#fecTimeoutMs,
1691
+ }
1692
+ }
1693
+
1694
+ #resolveTrackConfig(packetId: number): ResolvedFECTrackConfig {
1695
+ return this.#trackConfigs.get(packetId) ?? this.#defaultTrackConfig()
1696
+ }
1697
+
1698
+ #computeTimeout(config: {
1699
+ k: number
1700
+ interleaveDepthMs: number
1701
+ fps?: number
1702
+ timeoutMs?: number
1703
+ }): number {
1704
+ if (config.timeoutMs && config.timeoutMs > 0) return config.timeoutMs
1705
+ // Only a valid §5.1 ms interleave (>= MIN_INTERLEAVE_DEPTH_MS) drives the
1706
+ // timeout. A sub-floor value is a raw frame count (no fps to convert with);
1707
+ // fall back to the established #fecTimeoutMs rather than collapse to ~0.
1708
+ if (config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
1709
+ return Math.max(
1710
+ this.#fecTimeoutMs,
1711
+ computeFecDeliveryWindowMs({
1712
+ interleaveDepthMs: config.interleaveDepthMs,
1713
+ sourceSymbols: config.k,
1714
+ mediaUnitsPerSecond: config.fps,
1715
+ }),
1716
+ )
1717
+ }
1718
+ return this.#fecTimeoutMs
1719
+ }
1720
+
1721
+ /**
1722
+ * The delivery-gap window is the longest catalog keyframe interval among
1723
+ * the configured video streams. A failed video block costs every frame up
1724
+ * to the next keyframe, so a receiver must remember a stall for at least
1725
+ * that long: forgetting it sooner would let the next recurrence fail a
1726
+ * block whose damage outlives the memory of the stall that caused it. It
1727
+ * comes from the catalog's `keyframeIntervalTicks`/`keyframeIntervalMs`
1728
+ * (via the classifier geometry), never from a constant. It also caps the
1729
+ * gap the wait may absorb; with no catalog cadence no gap is reported and
1730
+ * the catalog tolerance alone applies (see DeliveryGapEstimator).
1731
+ */
1732
+ #refreshDeliveryGapWindow(): void {
1733
+ let windowMs: number | undefined
1734
+ const consider = (geometry: BlockClassifierGeometry | undefined): void => {
1735
+ if (geometry?.trackKind !== 'video' || geometry.mode !== 'classifying') return
1736
+ const { ticks, timescale } = geometry.keyframeInterval
1737
+ const ms = (ticks / timescale) * 1000
1738
+ if (Number.isFinite(ms) && ms > 0 && (windowMs === undefined || ms > windowMs)) windowMs = ms
1739
+ }
1740
+ for (const geometry of this.#streamGeometries.values()) consider(geometry)
1741
+ for (const config of this.#trackConfigs.values()) consider(config.geometry)
1742
+ this.#deliveryGaps.setWindowMs(windowMs)
1743
+ }
1744
+
1745
+ /**
1746
+ * The multicast late-symbol wait: the block span plus the larger of the
1747
+ * catalog's signaled tolerance and the receiver-measured delivery gap.
1748
+ *
1749
+ * `config.timeoutMs` already is span + `fec.reorderToleranceMs` (or the
1750
+ * wider envelope configure() applies), so it stays the floor; the measured
1751
+ * gap widens it only when the path stalls for longer than the catalog
1752
+ * allowed for. Datagram delivery only: an ordered relay settles blocks by
1753
+ * stream order and never feeds the estimator.
1754
+ */
1755
+ #multicastWaitMs(config: ResolvedFECTrackConfig): number {
1756
+ return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()))
1757
+ }
1758
+
1759
+ /**
1760
+ * The widest #multicastWaitMs can become: the estimator reports at most its
1761
+ * catalog window, so this is a catalog quantity that no measurement moves.
1762
+ */
1763
+ #maxMulticastWaitMs(config: ResolvedFECTrackConfig): number {
1764
+ return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0)
1765
+ }
1766
+
1767
+ #waitForGapMs(config: ResolvedFECTrackConfig, gapMs: number): number {
1768
+ if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs
1769
+ return Math.max(config.timeoutMs, Math.ceil(config.interleaveDepthMs + gapMs))
1770
+ }
1771
+
1772
+ #repairDeadlineMs(
1773
+ config: ResolvedFECTrackConfig,
1774
+ waitMs = this.#multicastWaitMs(config),
1775
+ ): number {
1776
+ const halfFailBoundMs = Math.ceil(waitMs / 2)
1777
+ if (
1778
+ config.k > 0 &&
1779
+ config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS &&
1780
+ config.fps !== undefined &&
1781
+ Number.isFinite(config.fps) &&
1782
+ config.fps > 0
1783
+ ) {
1784
+ const mediaUnitMs = 1000 / config.fps
1785
+ const interleaveUnits = deriveFecInterleaveDepth(
1786
+ config.interleaveDepthMs,
1787
+ mediaUnitMs,
1788
+ )
1789
+ const sourceHorizonMs = Math.ceil(config.k * interleaveUnits * mediaUnitMs)
1790
+ if (sourceHorizonMs < waitMs) return sourceHorizonMs
1791
+ }
1792
+ return halfFailBoundMs
1793
+ }
1794
+
1795
+ /**
1796
+ * One block lifetime: the inactivity fail bound plus the D-28 repair grace,
1797
+ * at the widest wait the catalog allows (#maxMulticastWaitMs). Everything
1798
+ * derived from it (terminal retention, the release gate's hold ceiling, the
1799
+ * duplicate ledgers, the owed-cleanup bound) is compared across time, so it
1800
+ * must not follow the live measurement.
1801
+ */
1802
+ #blockLifetimeMs(config: ResolvedFECTrackConfig): number {
1803
+ const waitMs = this.#maxMulticastWaitMs(config)
1804
+ return waitMs + this.#repairGraceMs(config, waitMs)
1805
+ }
1806
+
1807
+ /**
1808
+ * The lifetime at the live wait, capped at #blockLifetimeMs: lifetime is not
1809
+ * monotone in the wait (the repair deadline switches from half the wait to
1810
+ * the source horizon), so the cap is what keeps it inside the retention.
1811
+ */
1812
+ #liveBlockLifetimeMs(config: ResolvedFECTrackConfig): number {
1813
+ const waitMs = this.#multicastWaitMs(config)
1814
+ return Math.min(waitMs + this.#repairGraceMs(config, waitMs), this.#blockLifetimeMs(config))
1815
+ }
1816
+
1817
+ #repairGraceMs(config: ResolvedFECTrackConfig, waitMs: number): number {
1818
+ return Math.max(1, waitMs - this.#repairDeadlineMs(config, waitMs))
1819
+ }
1820
+
1821
+ #armBlockTimeout(
1822
+ sbn: number,
1823
+ packetId: number,
1824
+ catalogTrackName: string | undefined,
1825
+ delayMs: number,
1826
+ ): void {
1827
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
1828
+ const waitAtMs = performance.now() + Math.max(1, Math.ceil(delayMs))
1829
+ // A held block's symbols (its own FETCH's repair symbols included) never
1830
+ // carry its wait past the hold: the hold is its presentation deadline.
1831
+ const holdAtMs = this.#repairHoldUntilMs.get(key)
1832
+ this.#blockWaitDeadlinesMs.set(key, holdAtMs === undefined ? waitAtMs : Math.min(waitAtMs, holdAtMs))
1833
+ this.#applyBlockDeadline(key, sbn, packetId, catalogTrackName)
1834
+ }
1835
+
1836
+ /**
1837
+ * Arm (or move) a block's one fail timer at the later of its multicast
1838
+ * wait and its repair hold. Moving it later costs no timer operation: the
1839
+ * armed timer wakes no later than the new deadline and re-arms for the
1840
+ * remainder.
1841
+ */
1842
+ #applyBlockDeadline(
1843
+ key: string,
1844
+ sbn: number,
1845
+ packetId: number,
1846
+ catalogTrackName: string | undefined,
1847
+ ): void {
1848
+ const nowMs = performance.now()
1849
+ const deadlineMs = Math.max(
1850
+ this.#blockWaitDeadlinesMs.get(key) ?? nowMs + 1,
1851
+ this.#repairHoldUntilMs.get(key) ?? -Infinity,
1852
+ )
1853
+ this.#activeBlockDeadlinesMs.set(key, deadlineMs)
1854
+ const armed = this.#activeBlocks.get(key)
1855
+ if (armed?.handle != null) {
1856
+ if (armed.fireAtMs <= deadlineMs) return
1857
+ clearTimeout(armed.handle)
1858
+ }
1859
+ const timer: DeadlineTimer = { handle: null, fireAtMs: deadlineMs }
1860
+ const onFire = (): void => {
1861
+ // clearTimeout() cannot retract a callback that the browser already
1862
+ // moved onto its task queue. Only the timer that still owns this
1863
+ // block's deadline may fail it or enqueue Worker cleanup.
1864
+ if (this.#activeBlocks.get(key) !== timer) return
1865
+ const currentDeadlineMs = this.#activeBlockDeadlinesMs.get(key)
1866
+ const firedAtMs = performance.now()
1867
+ if (currentDeadlineMs !== undefined && currentDeadlineMs > firedAtMs) {
1868
+ timer.fireAtMs = currentDeadlineMs
1869
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - firedAtMs))
1870
+ return
1871
+ }
1872
+ this.#activeBlocks.delete(key)
1873
+ this.#activeBlockDeadlinesMs.delete(key)
1874
+ this.#blockWaitDeadlinesMs.delete(key)
1875
+ this.#repairHoldUntilMs.delete(key)
1876
+ this.#traceLifecycle('timeout-queued', sbn, packetId, catalogTrackName)
1877
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName)
1878
+ }
1879
+ timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)))
1880
+ this.#activeBlocks.set(key, timer)
1881
+ this.#indexBlockKey(key, sbn, packetId)
1882
+ }
1883
+
1884
+ /**
1885
+ * Hand a block whose delivery is over to its decoder for finalization: the
1886
+ * datagram deadline fired, or the ordered relay moved past it.
1887
+ */
1888
+ #finalizeExpiredBlock(
1889
+ sbn: number,
1890
+ packetId: number,
1891
+ catalogTrackName: string | undefined,
1892
+ ): void {
1893
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
1894
+ // A vanished block that never received a symbol holds no decoder state
1895
+ // to clean up; waiting on a Worker acknowledgement would never settle.
1896
+ if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
1897
+ this.#failBlock(sbn, packetId, catalogTrackName)
1898
+ return
1899
+ }
1900
+
1901
+ // A block that began on the synchronous decoder remains owned by that
1902
+ // decoder even if Worker setup completed later. Cleanup must follow the
1903
+ // same ownership rule as source and repair symbol dispatch.
1904
+ const syncOwner = this.#syncDecoderBlockOwners.get(key)
1905
+ if (syncOwner) {
1906
+ this.#routeSyncCleanup(syncOwner, sbn, packetId, catalogTrackName)
1907
+ this.#failBlock(sbn, packetId, catalogTrackName)
1908
+ return
1909
+ }
1910
+
1911
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName)
1912
+ if (workerClient) {
1913
+ this.#pendingWorkerCleanups.add(key)
1914
+ this.#pendingWorkerCleanupClients.set(key, workerClient)
1915
+ this.#boundOwedCleanup(key, packetId, workerClient)
1916
+ workerClient.cleanup(sbn)
1917
+ } else {
1918
+ const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client
1919
+ if (decoder) {
1920
+ this.#routeSyncCleanup(decoder, sbn, packetId, catalogTrackName)
1921
+ this.#failBlock(sbn, packetId, catalogTrackName)
1922
+ } else {
1923
+ this.#failBlock(sbn, packetId, catalogTrackName)
1924
+ }
1925
+ }
1926
+ }
1927
+
1928
+ /**
1929
+ * Upsert one packetId's track configuration. With `catalogTrackName`, the
1930
+ * classifier geometry in `config` is that stream's own and is kept per
1931
+ * stream; every other field stays per packetId.
1932
+ */
1933
+ #upsertTrackConfig(
1934
+ packetId: number,
1935
+ config: FECManagerConfig,
1936
+ catalogTrackName?: string,
1937
+ ): ResolvedFECTrackConfig {
1938
+ const previous = this.#trackConfigs.get(packetId) ?? this.#defaultTrackConfig()
1939
+ const streamScopedGeometry =
1940
+ catalogTrackName !== undefined && config.geometry !== undefined ? config.geometry : undefined
1941
+ if (streamScopedGeometry !== undefined) {
1942
+ const { geometry: _streamGeometry, ...packetLevel } = config
1943
+ config = packetLevel
1944
+ }
1945
+ const timingChanged =
1946
+ config.k !== undefined ||
1947
+ config.interleaveDepthMs !== undefined ||
1948
+ config.fps !== undefined
1949
+ if (config.blockProfile !== undefined) {
1950
+ parseFecBlockProfile(config.blockProfile, `packetId=${packetId} fec.blockProfile`)
1951
+ }
1952
+ const blockProfile = config.blockProfile ?? previous.blockProfile
1953
+ if (blockProfile === undefined) {
1954
+ throw new Error(
1955
+ `[FECManager] packetId=${packetId}: fec.blockProfile is required ` +
1956
+ '("iso-ssbg1-v1"); configure the track from its catalog',
1957
+ )
1958
+ }
1959
+ // iso-ssbg1-v1 block location keeps what it holds for a horizon derived
1960
+ // from this packet's catalog block span (#isoRetentionBlocks): without
1961
+ // one the locator would grow for the life of the session. The span is
1962
+ // this packet's own; the manager-wide default is never borrowed.
1963
+ const ownInterleaveDepthMs =
1964
+ config.interleaveDepthMs ?? this.#trackConfigs.get(packetId)?.interleaveDepthMs
1965
+ if (
1966
+ ownInterleaveDepthMs === undefined ||
1967
+ !Number.isFinite(ownInterleaveDepthMs) ||
1968
+ ownInterleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS
1969
+ ) {
1970
+ throw new Error(
1971
+ `[FECManager] packetId=${packetId}: iso-ssbg1-v1 requires the catalog fec.interleaveDepthMs ` +
1972
+ `(>= ${MIN_INTERLEAVE_DEPTH_MS} ms; got ${String(ownInterleaveDepthMs)}): it bounds how long ` +
1973
+ 'block location keeps stated blocks and held sources',
1974
+ )
1975
+ }
1976
+ const next: ResolvedFECTrackConfig = {
1977
+ blockProfile,
1978
+ k: config.k ?? previous.k,
1979
+ symbolSize:
1980
+ config.symbolSize != null && config.symbolSize > 0
1981
+ ? config.symbolSize
1982
+ : previous.symbolSize,
1983
+ interleaveDepthMs: config.interleaveDepthMs ?? previous.interleaveDepthMs,
1984
+ fps: config.fps ?? previous.fps,
1985
+ timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs),
1986
+ ...((config.trackKind ?? previous.trackKind) === undefined
1987
+ ? {}
1988
+ : { trackKind: config.trackKind ?? previous.trackKind }),
1989
+ ...((config.codec ?? previous.codec) === undefined
1990
+ ? {}
1991
+ : { codec: config.codec ?? previous.codec }),
1992
+ ...((config.geometry ?? previous.geometry) === undefined
1993
+ ? {}
1994
+ : { geometry: config.geometry ?? previous.geometry }),
1995
+ }
1996
+ next.timeoutMs = this.#computeTimeout(next)
1997
+ if (this.#multicastSymbolDelivery === 'ordered-relay') {
1998
+ // Error on bad init: an ordered-relay stream settles its blocks by the
1999
+ // decoder's interleave horizon, which this geometry must define.
2000
+ this.#orderedHorizonBlocksFor(packetId, next)
2001
+ }
2002
+ if (previous.blockProfile !== undefined && previous.k !== next.k) {
2003
+ // A different maximum K is a different block geometry: the stream's
2004
+ // blocks must not be read under the old one's rules.
2005
+ this.#dropIsoLocators(packetId)
2006
+ }
2007
+ this.#trackConfigs.set(packetId, next)
2008
+ this.#refreshDeliveryGapWindow()
2009
+ let policyChanged =
2010
+ (config.geometry !== undefined &&
2011
+ JSON.stringify(config.geometry) !== JSON.stringify(previous.geometry)) ||
2012
+ (config.trackKind !== undefined && config.trackKind !== previous.trackKind)
2013
+ if (streamScopedGeometry !== undefined) {
2014
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
2015
+ if (JSON.stringify(streamScopedGeometry) !== JSON.stringify(this.#streamGeometries.get(streamKey))) {
2016
+ this.#streamGeometries.set(streamKey, streamScopedGeometry)
2017
+ this.#refreshDeliveryGapWindow()
2018
+ policyChanged = true
2019
+ }
2020
+ }
2021
+ if (policyChanged) {
2022
+ // A new catalog epoch for this packet: every classifier whose geometry
2023
+ // changed rebuilds from the new one on its next symbol and announces
2024
+ // its mode again. A stream with its own geometry is untouched by a
2025
+ // sibling's change, but the first stream-scoped geometry on a packet
2026
+ // does change the siblings that have none (stream-geometry-absent).
2027
+ this.#bumpEpoch(packetId)
2028
+ for (const [key, classifier] of [...this.#classifiers]) {
2029
+ if (!this.#belongsToPacket(key, packetId)) continue
2030
+ const stream = this.#parseStreamKey(key)
2031
+ const geometry = this.#geometryFor(stream.packetId, stream.catalogTrackName)
2032
+ if (JSON.stringify(geometry) === JSON.stringify(classifier.geometry)) continue
2033
+ this.#classifiers.delete(key)
2034
+ // Blocks still unresolved lose the evidence their class rested on:
2035
+ // under the fresh classifier they read `unknown`. Say so, so a queued
2036
+ // or running P2 repair for a former delta block is promoted to P0
2037
+ // instead of silently keeping a priority its class no longer has.
2038
+ this.#applyClassifierChanges(stream.packetId, stream.catalogTrackName, classifier.retire())
2039
+ }
2040
+ }
2041
+ return next
2042
+ }
2043
+
2044
+ #blockKeysFor(sbn: number, packetId?: number, catalogTrackName?: string): string[] {
2045
+ if (packetId != null && catalogTrackName !== undefined) {
2046
+ return [this.#blockKey(sbn, packetId, catalogTrackName)]
2047
+ }
2048
+
2049
+ // Every key held by a block-keyed lookup set is indexed under its SBN
2050
+ // (#indexBlockKey), so this visits only the handful of streams sharing the
2051
+ // SBN instead of every retained block. #cleanlyCompletedBlocks is a subset
2052
+ // of #completedBlocks and needs no separate check.
2053
+ const keys: string[] = []
2054
+ const candidates = this.#blockKeysBySbn.get(sbn)
2055
+ if (candidates) {
2056
+ for (const [key, keyPacketId] of candidates) {
2057
+ if (packetId !== undefined && keyPacketId !== packetId) continue
2058
+ if (!this.#isBlockKeyHeld(key)) {
2059
+ candidates.delete(key)
2060
+ continue
2061
+ }
2062
+ keys.push(key)
2063
+ }
2064
+ if (candidates.size === 0) this.#blockKeysBySbn.delete(sbn)
2065
+ }
2066
+
2067
+ if (packetId !== undefined) {
2068
+ if (keys.length === 0) return [this.#blockKey(sbn, packetId)]
2069
+ return keys.length === 1 ? keys : []
2070
+ }
2071
+ return keys.length > 0 ? keys : [this.#blockKey(sbn, 0, catalogTrackName)]
2072
+ }
2073
+
2074
+ // -----------------------------------------------------------------------
2075
+ // Accessors
2076
+ // -----------------------------------------------------------------------
2077
+
2078
+ /** Internal state for diagnostics — not part of the public stats API. */
2079
+ get diagnostics() {
2080
+ return {
2081
+ timeoutMs: this.#fecTimeoutMs,
2082
+ activeBlocks: this.#activeBlocks.size,
2083
+ completedBlocks: this.#completedBlocks.size,
2084
+ cleanlyCompletedBlocks: this.#cleanlyCompletedBlocks.size,
2085
+ pendingCounts: Object.fromEntries(this.#blockSourceCounts),
2086
+ fpsDetected: this.#fpsDetected,
2087
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
2088
+ startupAlignedPackets: this.#packetIdsForStreamKeys(this.#startupAlignedPackets),
2089
+ startupPartialBlocks: this.#startupPartialBlocks.size,
2090
+ startupRepairReadyPackets: this.#packetIdsForStreamKeys(this.#startupRepairReadyPackets),
2091
+ startupRepairFailOpenPackets: this.#packetIdsForStreamKeys(this.#startupRepairFailOpenPackets),
2092
+ pendingWorkerCleanups: this.#pendingWorkerCleanups.size,
2093
+ decoderUnavailableEvents: this.#decoderUnavailableEvents,
2094
+ repairTrackedBlocks: this.#blockRepairRsIds.size,
2095
+ multicastSymbolDelivery: this.#multicastSymbolDelivery,
2096
+ orderedFrontiers: Object.fromEntries(this.#orderedFrontiers),
2097
+ orderedPendingBlocks: [...this.#orderedPendingBlocks.values()]
2098
+ .reduce((total, pending) => total + pending.size, 0),
2099
+ lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry })),
2100
+ }
2101
+ }
2102
+
2103
+ get fecStats(): FecStats {
2104
+ const s = this.#fecStats
2105
+ const affected = s.blocksRecovered + s.blocksFailed
2106
+ const total = s.blocksClean + affected
2107
+ const tracks = [...this.#fecTrackStats.entries()]
2108
+ .sort(([left], [right]) => left - right)
2109
+ .map(([packetId, stats]) => {
2110
+ const trackAffected = stats.blocksRecovered + stats.blocksFailed
2111
+ const trackTotal = stats.blocksClean + trackAffected
2112
+ return {
2113
+ ...stats,
2114
+ packetId,
2115
+ blocksComplete: trackTotal,
2116
+ k: this.#resolveTrackConfig(packetId).k,
2117
+ recoveryRate: trackAffected > 0
2118
+ ? (stats.blocksRecovered / trackAffected) * 100
2119
+ : 100,
2120
+ packetLossRate: trackTotal > 0 ? (trackAffected / trackTotal) * 100 : 0,
2121
+ }
2122
+ })
2123
+ return {
2124
+ ...s,
2125
+ blocksComplete: total,
2126
+ mixedPathBlocks: Array.from(this.#blockPathCounts.values()).filter(
2127
+ (block) => block.multicastSymbols > 0 && block.moqSymbols > 0,
2128
+ ).length,
2129
+ recentBlockPathCounts: Array.from(this.#blockPathCounts.values()).slice(-24),
2130
+ k: this.#fecK,
2131
+ // True recovery rate: of blocks that HAD loss, how many were recovered?
2132
+ recoveryRate: affected > 0 ? (s.blocksRecovered / affected) * 100 : 100,
2133
+ packetLossRate: total > 0 ? (affected / total) * 100 : 0,
2134
+ tracks,
2135
+ workers: [...this.#fecWorkerStats.entries()]
2136
+ .sort(([left], [right]) => left - right)
2137
+ .map(([packetId, stats]) => ({
2138
+ ...stats,
2139
+ config: {
2140
+ ...stats.config,
2141
+ resolution: stats.config.resolution ? { ...stats.config.resolution } : undefined,
2142
+ },
2143
+ blocks: stats.blocks.map((block) => ({ ...block })),
2144
+ decoder: stats.decoder ? { ...stats.decoder } : undefined,
2145
+ altaFailedDetails: stats.altaFailedDetails?.map((detail) => ({ ...detail })),
2146
+ packetId,
2147
+ })),
2148
+ repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
2149
+ workerErrors: Object.fromEntries(this.#workerErrorCounts),
2150
+ }
2151
+ }
2152
+
2153
+ /**
2154
+ * Observe Worker-backed per-track snapshots without taking ownership of the
2155
+ * legacy single-callback slot. Infrastructure diagnostics and a player may
2156
+ * therefore consume the same source event without wrapping or replacing one
2157
+ * another's callback.
2158
+ */
2159
+ addFecStatsObserver(
2160
+ observer: (packetId: number, stats: FecTrackStats) => void,
2161
+ ): () => void {
2162
+ this.#fecStatsObservers.add(observer)
2163
+ return () => this.#fecStatsObservers.delete(observer)
2164
+ }
2165
+
2166
+ /** Start a new multicast transport join without discarding track/decoder state. */
2167
+ beginMulticastJoin(): void {
2168
+ // A new subscription is a new relay: stream order is only defined within
2169
+ // one. Blocks still pending from the last join settle once the new
2170
+ // stream's own frontier passes them.
2171
+ this.#orderedFrontiers.clear()
2172
+ this.#startupAlignedPackets.clear()
2173
+ this.#startupPartialBlocks.clear()
2174
+ this.#startupRequireRepairReady = true
2175
+ this.#startupRepairReadyPackets.clear()
2176
+ this.#startupRepairBoundaryCounts.clear()
2177
+ this.#startupRepairFailOpenPackets.clear()
2178
+ }
2179
+
2180
+ /** How the multicast leg currently delivers symbols. */
2181
+ get multicastSymbolDelivery(): MulticastSymbolDelivery {
2182
+ return this.#multicastSymbolDelivery
2183
+ }
2184
+
2185
+ /**
2186
+ * Declare how the multicast leg delivers symbols (see
2187
+ * MulticastSymbolDelivery). The multicast provider owns this fact:
2188
+ * MulticastManager applies what the window.multicast subscription declares
2189
+ * on every join, and a consumer feeding packets itself declares its own leg.
2190
+ *
2191
+ * Switching to 'ordered-relay' requires every configured track to define
2192
+ * its interleave horizon and throws otherwise. Switching back to 'datagram'
2193
+ * gives every block awaiting ordered settlement the datagram inactivity
2194
+ * deadline from now.
2195
+ */
2196
+ setMulticastSymbolDelivery(delivery: MulticastSymbolDelivery): void {
2197
+ if (!isMulticastSymbolDelivery(delivery)) {
2198
+ throw new Error(
2199
+ `[FECManager] multicast symbol delivery must be 'datagram' or ` +
2200
+ `'ordered-relay', got ${String(delivery)}`,
2201
+ )
2202
+ }
2203
+ if (delivery === this.#multicastSymbolDelivery) return
2204
+ // A different delivery path: gaps measured on the old one say nothing
2205
+ // about it (and ordered-relay never feeds the estimator).
2206
+ this.#deliveryGaps.reset()
2207
+ if (delivery === 'ordered-relay') {
2208
+ for (const [packetId, config] of this.#trackConfigs) {
2209
+ this.#orderedHorizonBlocksFor(packetId, config)
2210
+ }
2211
+ this.#multicastSymbolDelivery = delivery
2212
+ return
2213
+ }
2214
+ this.#multicastSymbolDelivery = delivery
2215
+ const pending = [...this.#orderedPendingBlocks.values()]
2216
+ .flatMap((blocks) => [...blocks.values()])
2217
+ this.#orderedPendingBlocks.clear()
2218
+ this.#orderedFrontiers.clear()
2219
+ for (const key of pending) {
2220
+ const block = this.#parseBlockKey(key)
2221
+ this.noteBlockActivity(block.sbn, block.packetId, block.catalogTrackName)
2222
+ }
2223
+ }
2224
+
2225
+ /** Begin a fresh decode epoch for one physical stream. */
2226
+ resetTrack(packetId: number, catalogTrackName: string): void {
2227
+ if (!Number.isInteger(packetId) || packetId < 0) {
2228
+ throw new Error(`[FECManager] invalid packetId for reset: ${packetId}`)
2229
+ }
2230
+ if (!catalogTrackName) {
2231
+ throw new Error('[FECManager] catalogTrackName is required for track reset')
2232
+ }
2233
+ const resetMap = <T>(map: Map<string, T>): void => {
2234
+ for (const key of map.keys()) {
2235
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue
2236
+ map.delete(key)
2237
+ }
2238
+ }
2239
+ const resetTimerMap = (map: Map<string, DeadlineTimer | null>): void => {
2240
+ for (const [key, timer] of map) {
2241
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue
2242
+ if (timer?.handle != null) clearTimeout(timer.handle)
2243
+ map.delete(key)
2244
+ }
2245
+ }
2246
+ const resetSet = (set: Set<string>): void => {
2247
+ for (const key of set) {
2248
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) set.delete(key)
2249
+ }
2250
+ }
2251
+
2252
+ resetTimerMap(this.#activeBlocks)
2253
+ resetTimerMap(this.#repairDeadlines)
2254
+ resetMap(this.#activeBlockDeadlinesMs)
2255
+ resetMap(this.#blockWaitDeadlinesMs)
2256
+ resetMap(this.#repairHoldUntilMs)
2257
+ resetMap(this.#repairDeadlineAtMs)
2258
+ // Queued terminal records of this stream no longer match an expiry entry,
2259
+ // so the retirement sweep skips them and cannot retire a reused key early.
2260
+ resetMap(this.#terminalExpiryMs)
2261
+ resetMap(this.#pendingWorkerCleanupClients)
2262
+ for (const key of [...this.#pendingWorkerCleanupBounds.keys()]) {
2263
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) this.#clearOwedCleanupBound(key)
2264
+ }
2265
+ resetMap(this.#blockSourceCounts)
2266
+ resetMap(this.#blockSourceEsis)
2267
+ resetMap(this.#blockAuthoredLengths)
2268
+ resetMap(this.#blockRepairRsIds)
2269
+ resetMap(this.#blockPathCounts)
2270
+ resetMap(this.#blockAnchorsMs)
2271
+ resetMap(this.#blockCatalogTrackNames)
2272
+ resetMap(this.#syncDecoderBlockOwners)
2273
+ resetMap(this.#startupRepairBoundaryCounts)
2274
+ resetMap(this.#orderedFrontiers)
2275
+ resetMap(this.#orderedPendingBlocks)
2276
+ resetSet(this.#pendingWorkerCleanups)
2277
+ resetSet(this.#completedBlocks)
2278
+ resetSet(this.#cleanlyCompletedBlocks)
2279
+ resetSet(this.#repairRequestedBlocks)
2280
+ resetSet(this.#workerRecoveredBlocks)
2281
+ resetSet(this.#startupAlignedPackets)
2282
+ resetSet(this.#startupPartialBlocks)
2283
+ resetSet(this.#startupRepairReadyPackets)
2284
+ resetSet(this.#startupRepairFailOpenPackets)
2285
+ resetSet(this.#seenSymbols)
2286
+ resetSet(this.#failedBlocks)
2287
+ resetSet(this.#repairedBlocks)
2288
+ resetSet(this.#materializedBlocks)
2289
+ resetMap(this.#resolvedBlockClasses)
2290
+ resetMap(this.#highestSbn)
2291
+ resetMap(this.#isoLocators)
2292
+ resetMap(this.#sourceAnchors)
2293
+ this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName))
2294
+ this.#bumpEpoch(packetId)
2295
+ for (const [sbn, keys] of this.#blockKeysBySbn) {
2296
+ for (const key of keys.keys()) {
2297
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) keys.delete(key)
2298
+ }
2299
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn)
2300
+ }
2301
+
2302
+ const decoderClients = new Set<WasmFecDecoder>()
2303
+ for (const [key, entry] of this.#fecDecoders) {
2304
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) {
2305
+ decoderClients.add(entry.client)
2306
+ }
2307
+ }
2308
+ const clients = new Set<object>()
2309
+ for (const client of decoderClients) {
2310
+ if (
2311
+ typeof client.flush === 'function' &&
2312
+ typeof client.reset_stats === 'function'
2313
+ ) {
2314
+ try {
2315
+ client.flush()
2316
+ client.reset_stats()
2317
+ clients.add(client)
2318
+ } catch {
2319
+ this.#discardFecDecoderClient(client)
2320
+ }
2321
+ } else {
2322
+ this.#discardFecDecoderClient(client)
2323
+ }
2324
+ }
2325
+ for (const [key, client] of [...this.#workerClients]) {
2326
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue
2327
+ if (client.disposed === true) {
2328
+ // reset() throws on a disposed client; evict it (reporting the
2329
+ // decoder unavailable) instead of resetting a Worker that is gone.
2330
+ this.#evictDisposedWorker(client)
2331
+ continue
2332
+ }
2333
+ client.reset()
2334
+ clients.add(client)
2335
+ }
2336
+ for (const client of clients) this.#resetDecoderBlockOwners(client, catalogTrackName)
2337
+ }
2338
+
2339
+ /**
2340
+ * Retire one packet ID, drop-only: forget every stream on it (block
2341
+ * ledgers, deadlines and their timers, repair holds, terminal records,
2342
+ * classifiers, stream geometry), its per-packet configuration and
2343
+ * statistics, and take its decoders out of routing.
2344
+ *
2345
+ * This is the end of the packet ID's streams, not a new epoch of them (that
2346
+ * is resetTrack): afterwards isTrackConfigured() is false and nothing about
2347
+ * it remains until it is configured again. Nothing is reported, because
2348
+ * nothing happened to the media: no block fails, recovers or resolves, no
2349
+ * repair resolves, and no decoder becomes "unavailable" (a retired stream
2350
+ * has no symbols left to decode, so a decoder-unavailable event would
2351
+ * describe lost protection that no stream suffers). The epoch still
2352
+ * advances, so a gap decision made before the retirement never matches a
2353
+ * stream later configured on the same packet ID.
2354
+ *
2355
+ * Decoder and Worker clients stay caller-owned: each is flushed or reset so
2356
+ * it holds no block of the retired streams, then released from routing;
2357
+ * dispose it after this returns. Cumulative totals in fecStats keep what
2358
+ * the retired streams contributed.
2359
+ */
2360
+ releasePacket(packetId: number): void {
2361
+ if (!Number.isInteger(packetId) || packetId < 0) {
2362
+ throw new Error(`[FECManager] invalid packetId for release: ${packetId}`)
2363
+ }
2364
+ const onPacket = (key: string): boolean => this.#belongsToPacket(key, packetId)
2365
+ const dropMap = <T>(map: Map<string, T>): void => {
2366
+ for (const key of [...map.keys()]) if (onPacket(key)) map.delete(key)
2367
+ }
2368
+ const dropTimerMap = (map: Map<string, DeadlineTimer | null>): void => {
2369
+ for (const [key, timer] of [...map]) {
2370
+ if (!onPacket(key)) continue
2371
+ if (timer?.handle != null) clearTimeout(timer.handle)
2372
+ map.delete(key)
2373
+ }
2374
+ }
2375
+ const dropSet = (set: Set<string>): void => {
2376
+ for (const key of [...set]) if (onPacket(key)) set.delete(key)
2377
+ }
2378
+
2379
+ dropTimerMap(this.#activeBlocks)
2380
+ dropTimerMap(this.#repairDeadlines)
2381
+ for (const key of [...this.#pendingWorkerCleanupBounds.keys()]) {
2382
+ if (onPacket(key)) this.#clearOwedCleanupBound(key)
2383
+ }
2384
+ dropMap(this.#activeBlockDeadlinesMs)
2385
+ dropMap(this.#blockWaitDeadlinesMs)
2386
+ dropMap(this.#repairHoldUntilMs)
2387
+ dropMap(this.#repairDeadlineAtMs)
2388
+ dropMap(this.#terminalExpiryMs)
2389
+ dropMap(this.#pendingWorkerCleanupClients)
2390
+ dropMap(this.#blockSourceCounts)
2391
+ dropMap(this.#blockSourceEsis)
2392
+ dropMap(this.#blockAuthoredLengths)
2393
+ dropMap(this.#blockRepairRsIds)
2394
+ dropMap(this.#blockPathCounts)
2395
+ dropMap(this.#blockAnchorsMs)
2396
+ dropMap(this.#blockCatalogTrackNames)
2397
+ dropMap(this.#syncDecoderBlockOwners)
2398
+ dropMap(this.#startupRepairBoundaryCounts)
2399
+ dropMap(this.#orderedFrontiers)
2400
+ dropMap(this.#orderedPendingBlocks)
2401
+ dropMap(this.#resolvedBlockClasses)
2402
+ dropMap(this.#highestSbn)
2403
+ dropMap(this.#isoLocators)
2404
+ dropMap(this.#sourceAnchors)
2405
+ dropMap(this.#classifiers)
2406
+ dropMap(this.#streamGeometries)
2407
+ dropSet(this.#pendingWorkerCleanups)
2408
+ dropSet(this.#completedBlocks)
2409
+ dropSet(this.#cleanlyCompletedBlocks)
2410
+ dropSet(this.#repairRequestedBlocks)
2411
+ dropSet(this.#workerRecoveredBlocks)
2412
+ dropSet(this.#startupAlignedPackets)
2413
+ dropSet(this.#startupPartialBlocks)
2414
+ dropSet(this.#startupRepairReadyPackets)
2415
+ dropSet(this.#startupRepairFailOpenPackets)
2416
+ dropSet(this.#seenSymbols)
2417
+ dropSet(this.#failedBlocks)
2418
+ dropSet(this.#repairedBlocks)
2419
+ dropSet(this.#materializedBlocks)
2420
+ for (const [sbn, keys] of [...this.#blockKeysBySbn]) {
2421
+ for (const [key, keyPacketId] of [...keys]) {
2422
+ if (keyPacketId === packetId) keys.delete(key)
2423
+ }
2424
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn)
2425
+ }
2426
+ this.#terminalQueues.delete(packetId)
2427
+
2428
+ // Bookkeeping first: a decoder or Worker client whose teardown throws must
2429
+ // not leave the packet ID configured or its epoch unbumped, or a gap
2430
+ // decision made before the release could match a stream later configured
2431
+ // on the same packet ID.
2432
+ this.#trackConfigs.delete(packetId)
2433
+ this.#fecTrackStats.delete(packetId)
2434
+ this.#fecWorkerStats.delete(packetId)
2435
+ this.#bumpEpoch(packetId)
2436
+ // The retired stream's keyframe cadence no longer widens the gap window.
2437
+ // The delivery-gap estimator's per-packet sequence is kept: it measures
2438
+ // the link, which the retired packet ID's datagrams still describe while
2439
+ // a rendition-stable allow-list keeps delivering them.
2440
+ this.#refreshDeliveryGapWindow()
2441
+
2442
+ for (const [key, entry] of [...this.#fecDecoders]) {
2443
+ if (!onPacket(key)) continue
2444
+ this.#fecDecoders.delete(key)
2445
+ this.#decoderBlockOwners.delete(entry.client)
2446
+ try {
2447
+ entry.client.flush?.()
2448
+ } catch {
2449
+ // The client is leaving routing either way; a decoder that cannot
2450
+ // flush holds nothing this manager will ask it for again.
2451
+ }
2452
+ }
2453
+ for (const [key, client] of [...this.#workerClients]) {
2454
+ if (!onPacket(key)) continue
2455
+ this.#workerClients.delete(key)
2456
+ this.#decoderBlockOwners.delete(client)
2457
+ this.#releasedWorkerClients.add(client)
2458
+ try {
2459
+ if (client.disposed !== true) client.reset()
2460
+ } catch {
2461
+ // Already out of routing, and its late messages are ignored
2462
+ // (#releasedWorkerClients); a Worker that cannot reset holds nothing
2463
+ // this manager will ask it for again.
2464
+ }
2465
+ }
2466
+ }
2467
+
2468
+ /**
2469
+ * Record a transport symbol and reject later duplicates of the same
2470
+ * packetId/SBN/ESI. `sbn` is the block's SS_Start. A packetId with no
2471
+ * configured block profile has no block geometry: its symbol is refused
2472
+ * (false) and no block state is created for it.
2473
+ */
2474
+ feedSymbolFromSource(
2475
+ packetId: number,
2476
+ sbn: number,
2477
+ esi: number,
2478
+ _data: Uint8Array,
2479
+ source: FecSymbolSource,
2480
+ catalogTrackName?: string,
2481
+ ): boolean {
2482
+ if (!this.#hasBlockProfile(packetId)) return false
2483
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName)
2484
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
2485
+ if (source === 'multicast' && this.#multicastSymbolDelivery === 'ordered-relay') {
2486
+ // Every multicast symbol is a stream position on an ordered relay, even
2487
+ // one refused below as a join partial or a duplicate.
2488
+ this.#advanceOrderedFrontier(streamKey, sbn, packetId, catalogTrackName)
2489
+ }
2490
+ // Repair ESIs start at the block's own SSB_length (K'), which its locator
2491
+ // states once a repair placed it; before that, K is the only bound.
2492
+ const sourceSymbols =
2493
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.kForPacket(packetId)
2494
+ const isSourceSymbol = esi >= 0 && esi < sourceSymbols
2495
+ const isStartupPartial = this.#startupPartialBlocks.has(blockKey)
2496
+ const isReadyMulticastRepair =
2497
+ this.#startupRequireRepairReady &&
2498
+ source === 'multicast' &&
2499
+ !isSourceSymbol &&
2500
+ this.#startupRepairReadyPackets.has(streamKey)
2501
+ const awaitingMulticastRepair =
2502
+ this.#startupRequireRepairReady &&
2503
+ source === 'multicast' &&
2504
+ !this.#startupRepairReadyPackets.has(streamKey) &&
2505
+ !this.#startupRepairFailOpenPackets.has(streamKey)
2506
+ if (awaitingMulticastRepair) {
2507
+ if (!isSourceSymbol) {
2508
+ this.#startupRepairReadyPackets.add(streamKey)
2509
+ this.#startupRepairBoundaryCounts.delete(streamKey)
2510
+ this.#markStartupPartial(blockKey)
2511
+ return false
2512
+ }
2513
+
2514
+ if (esi === 0) {
2515
+ const boundaries = (this.#startupRepairBoundaryCounts.get(streamKey) ?? 0) + 1
2516
+ this.#startupRepairBoundaryCounts.set(streamKey, boundaries)
2517
+ if (boundaries >= STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES) {
2518
+ this.#startupRepairBoundaryCounts.delete(streamKey)
2519
+ this.#startupRepairFailOpenPackets.add(streamKey)
2520
+ } else {
2521
+ this.#markStartupPartial(blockKey)
2522
+ return false
2523
+ }
2524
+ } else {
2525
+ this.#markStartupPartial(blockKey)
2526
+ return false
2527
+ }
2528
+ }
2529
+ if (isSourceSymbol && esi === 0) {
2530
+ // ESI=0 establishes a complete source boundary for this SBN. Remove
2531
+ // only this block: other interleaved SBNs may still be join partials.
2532
+ this.#startupPartialBlocks.delete(blockKey)
2533
+ this.#startupAlignedPackets.add(streamKey)
2534
+ } else if (
2535
+ (isStartupPartial && !isReadyMulticastRepair) ||
2536
+ (!this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair)
2537
+ ) {
2538
+ this.#markStartupPartial(blockKey)
2539
+ return false
2540
+ }
2541
+
2542
+ // A completed block remains authoritative after its individual symbol
2543
+ // identities age out of the bounded #seenSymbols cache. Without this
2544
+ // guard, a delayed copy from the other transport can recreate the block
2545
+ // inside a Worker decoder; that orphan never receives the full source and
2546
+ // repair set, so cleanup later reports a false failure/green fill.
2547
+ if (this.#completedBlocks.has(blockKey)) {
2548
+ this.#fecStats.duplicateSymbols++
2549
+ this.#statsForPacket(packetId).duplicateSymbols++
2550
+ return false
2551
+ }
2552
+
2553
+ const symbolKey = `${blockKey}:${esi}`
2554
+ if (this.#seenSymbols.has(symbolKey)) {
2555
+ this.#fecStats.duplicateSymbols++
2556
+ this.#statsForPacket(packetId).duplicateSymbols++
2557
+ return false
2558
+ }
2559
+ this.#seenSymbols.add(symbolKey)
2560
+
2561
+ const counts = this.#blockPathCounts.get(blockKey) ?? {
2562
+ packetId,
2563
+ sbn,
2564
+ ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
2565
+ multicastSymbols: 0,
2566
+ moqSymbols: 0,
2567
+ complete: false,
2568
+ }
2569
+ // The block's absolute anchor (fecBlockDeadlineMs): the receiver-local
2570
+ // time of its first accepted symbol, from which its presentation deadline
2571
+ // is measured.
2572
+ if (!this.#blockAnchorsMs.has(blockKey)) this.#blockAnchorsMs.set(blockKey, performance.now())
2573
+ if (source === 'multicast') counts.multicastSymbols++
2574
+ else counts.moqSymbols++
2575
+ this.#blockPathCounts.set(blockKey, counts)
2576
+ this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName)
2577
+
2578
+ // Keep the newest entries of each bounded cache. Deleting the oldest in
2579
+ // place keeps exactly the entries a slice(-n) rebuild would, without
2580
+ // copying the whole collection into an array on the page thread.
2581
+ if (this.#seenSymbols.size > 4096) {
2582
+ dropOldest(this.#seenSymbols, this.#seenSymbols.size - 2048)
2583
+ }
2584
+ if (this.#blockPathCounts.size > 512) {
2585
+ dropOldest(this.#blockPathCounts, this.#blockPathCounts.size - 256)
2586
+ }
2587
+ if (this.#blockAnchorsMs.size > 512) {
2588
+ dropOldest(this.#blockAnchorsMs, this.#blockAnchorsMs.size - 256)
2589
+ }
2590
+ if (this.#blockCatalogTrackNames.size > 512) {
2591
+ for (const key of dropOldest(
2592
+ this.#blockCatalogTrackNames,
2593
+ this.#blockCatalogTrackNames.size - 256,
2594
+ )) {
2595
+ this.#unindexBlockKey(key)
2596
+ }
2597
+ }
2598
+
2599
+ return true
2600
+ }
2601
+
2602
+ #observeBlockCatalogTrackName(
2603
+ blockKey: string,
2604
+ sbn: number,
2605
+ packetId: number,
2606
+ catalogTrackName?: string,
2607
+ ): void {
2608
+ if (catalogTrackName === undefined) return
2609
+ if (!this.#blockCatalogTrackNames.has(blockKey)) {
2610
+ this.#blockCatalogTrackNames.set(blockKey, catalogTrackName)
2611
+ this.#indexBlockKey(blockKey, sbn, packetId)
2612
+ return
2613
+ }
2614
+ if (this.#blockCatalogTrackNames.get(blockKey) !== catalogTrackName) {
2615
+ this.#blockCatalogTrackNames.set(blockKey, null)
2616
+ }
2617
+ }
2618
+
2619
+ /** Exact catalog identity retained for async recovery, if unambiguous. */
2620
+ catalogTrackNameForBlock(
2621
+ sbn: number,
2622
+ packetId: number,
2623
+ catalogTrackName?: string,
2624
+ ): string | undefined {
2625
+ if (catalogTrackName !== undefined) {
2626
+ return this.#blockCatalogTrackNames.get(
2627
+ this.#blockKey(sbn, packetId, catalogTrackName),
2628
+ ) ?? undefined
2629
+ }
2630
+ const names = new Set<string>()
2631
+ for (const [key, name] of this.#blockCatalogTrackNames) {
2632
+ const block = this.#parseBlockKey(key)
2633
+ if (block.packetId === packetId && block.sbn === sbn && name !== null) names.add(name)
2634
+ }
2635
+ return names.size === 1 ? [...names][0] : undefined
2636
+ }
2637
+
2638
+ #markStartupPartial(blockKey: string): void {
2639
+ this.#startupPartialBlocks.add(blockKey)
2640
+ if (this.#startupPartialBlocks.size > 128) {
2641
+ this.#startupPartialBlocks = new Set(
2642
+ Array.from(this.#startupPartialBlocks).slice(-64),
2643
+ )
2644
+ }
2645
+ }
2646
+
2647
+ /** Per-block state snapshot for FecBlockGrid visualization.
2648
+ * Returns the most recent blocks (active + recently completed). */
2649
+ getBlockStates(): Array<{
2650
+ sbn: number;
2651
+ packetId?: number;
2652
+ state: 'collecting' | 'complete' | 'failed';
2653
+ sourceCount: number;
2654
+ k: number;
2655
+ progress: number;
2656
+ }> {
2657
+ const blocks: Array<{ sbn: number; packetId?: number; state: 'collecting' | 'complete' | 'failed'; sourceCount: number; k: number; progress: number }> = [];
2658
+ // Active blocks (still collecting symbols)
2659
+ for (const [key] of this.#activeBlocks) {
2660
+ const { packetId, sbn } = this.#parseBlockKey(key);
2661
+ const count = this.#blockSourceCounts.get(key) ?? 0;
2662
+ const k = this.#blockAuthoredLengths.get(key) ?? this.kForPacket(packetId);
2663
+ blocks.push({ sbn, packetId, state: 'collecting', sourceCount: count, k, progress: k > 0 ? Math.min(count / k, 1) : 0 });
2664
+ }
2665
+ // Recently completed blocks (last 16)
2666
+ const completed = [...this.#completedBlocks].slice(-16);
2667
+ for (const key of completed) {
2668
+ const { packetId, sbn } = this.#parseBlockKey(key);
2669
+ if (!this.#activeBlocks.has(key)) {
2670
+ const k = this.kForPacket(packetId);
2671
+ blocks.push({ sbn, packetId, state: 'complete', sourceCount: k, k, progress: 1 });
2672
+ }
2673
+ }
2674
+ blocks.sort((a, b) => a.sbn - b.sbn || (a.packetId ?? 0) - (b.packetId ?? 0));
2675
+ return blocks.slice(-24); // cap at 24 most recent
2676
+ }
2677
+
2678
+ /** The raw WASM decoder for stats access (first registered decoder) */
2679
+ get wasmDecoder(): WasmFecDecoder | null {
2680
+ return this.#fecDecoders.values().next().value?.client ?? null
2681
+ }
2682
+
2683
+ get k(): number { return this.#fecK }
2684
+ kForPacket(packetId: number): number { return this.#resolveTrackConfig(packetId).k }
2685
+ /** FEC symbol size in bytes. */
2686
+ get symbolSize(): number { return this.#fecSymbolSize }
2687
+ symbolSizeForPacket(packetId: number): number { return this.#resolveTrackConfig(packetId).symbolSize }
2688
+ /** FEC block span in milliseconds (0 = no interleaving). */
2689
+ get interleaveDepthMs(): number { return this.#fecInterleaveDepthMs }
2690
+ interleaveDepthMsForPacket(packetId: number): number { return this.#resolveTrackConfig(packetId).interleaveDepthMs }
2691
+ /**
2692
+ * Record one multicast MMTP packet arrival (every packet of the leg, FEC
2693
+ * symbol or not) for the delivery-gap measurement. `packetSequenceNumber`
2694
+ * is the MMTP packet_sequence_number, which increments by one per packet of
2695
+ * a packet_id: it is what separates a stall from a loss (see
2696
+ * DeliveryGapEstimator). Datagram delivery only.
2697
+ */
2698
+ noteMulticastArrival(packetId: number, packetSequenceNumber: number): void {
2699
+ if (this.#multicastSymbolDelivery !== 'datagram') return
2700
+ this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber)
2701
+ }
2702
+ /**
2703
+ * Resolved per-track multicast late-symbol wait in milliseconds: the span
2704
+ * plus the larger of the catalog tolerance and the measured delivery gap.
2705
+ */
2706
+ timeoutMsForPacket(packetId: number): number {
2707
+ return this.#multicastWaitMs(this.#resolveTrackConfig(packetId))
2708
+ }
2709
+ /**
2710
+ * Largest multicast delivery gap measured over the current window (ms), and
2711
+ * that window (undefined: held since the last reset). Diagnostics.
2712
+ */
2713
+ multicastDeliveryGap(): { peakGapMs: number; windowMs: number | undefined } {
2714
+ return {
2715
+ peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
2716
+ windowMs: this.#deliveryGaps.windowMs,
2717
+ }
2718
+ }
2719
+ /**
2720
+ * Receiver-local time of a block's first accepted symbol, or undefined for
2721
+ * a block no symbol reached (one materialized because a later SBN arrived).
2722
+ */
2723
+ blockAnchorAtMs(sbn: number, packetId: number, catalogTrackName?: string): number | undefined {
2724
+ return this.#blockAnchorsMs.get(this.#blockKey(sbn, packetId, catalogTrackName))
2725
+ }
2726
+ /** Absolute fail deadline of a still-open block, or undefined. */
2727
+ blockDeadlineAtMs(sbn: number, packetId: number, catalogTrackName?: string): number | undefined {
2728
+ return this.#activeBlockDeadlinesMs.get(this.#blockKey(sbn, packetId, catalogTrackName))
2729
+ }
2730
+ /**
2731
+ * Keep a block open until `untilAtMs` while a repair FETCH the scheduler
2732
+ * admitted is in flight. Never shortens the multicast wait already armed;
2733
+ * while set, the hold is the block's whole deadline, so no later symbol
2734
+ * extends it. Returns false when the block is no longer open (resolved, or
2735
+ * not yet tracked).
2736
+ */
2737
+ holdBlockForRepair(
2738
+ sbn: number,
2739
+ packetId: number,
2740
+ catalogTrackName: string | undefined,
2741
+ untilAtMs: number,
2742
+ ): boolean {
2743
+ if (!Number.isFinite(untilAtMs)) {
2744
+ throw new Error(`[FECManager] repair hold must be a finite time (got ${untilAtMs})`)
2745
+ }
2746
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
2747
+ if (!this.#activeBlocks.has(key)) return false
2748
+ const previous = this.#repairHoldUntilMs.get(key)
2749
+ if (previous !== undefined && previous >= untilAtMs) return true
2750
+ // The hold absorbs the wait already armed, so it never shortens it.
2751
+ this.#repairHoldUntilMs.set(
2752
+ key,
2753
+ Math.max(untilAtMs, this.#blockWaitDeadlinesMs.get(key) ?? -Infinity),
2754
+ )
2755
+ this.#applyBlockDeadline(key, sbn, packetId, catalogTrackName)
2756
+ return true
2757
+ }
2758
+ /**
2759
+ * Drop a block's repair hold: its FETCH ended without delivering. The block
2760
+ * falls back to its multicast wait, which may already have passed.
2761
+ */
2762
+ releaseRepairHold(sbn: number, packetId: number, catalogTrackName?: string): void {
2763
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
2764
+ if (!this.#repairHoldUntilMs.delete(key) || !this.#activeBlocks.has(key)) return
2765
+ this.#applyBlockDeadline(key, sbn, packetId, catalogTrackName)
2766
+ }
2767
+ /** Resolved per-track D-28 repair request deadline in milliseconds. */
2768
+ repairDeadlineMsForPacket(packetId: number): number {
2769
+ return this.#repairDeadlineMs(this.#resolveTrackConfig(packetId))
2770
+ }
2771
+ /**
2772
+ * One block lifetime: the longest a block stays open after its last symbol
2773
+ * (inactivity fail bound plus D-28 repair grace).
2774
+ */
2775
+ blockLifetimeMsForPacket(packetId: number): number {
2776
+ return this.#blockLifetimeMs(this.#resolveTrackConfig(packetId))
2777
+ }
2778
+ /**
2779
+ * How long a terminal (clean, recovered or failed) block stays authoritative,
2780
+ * for late symbols and for the in-order release gate. It is also the gate's
2781
+ * hold ceiling (MmtpRouter's holdLimitMs): a retired block reads back as
2782
+ * untracked, which the gate counts as lost, so no frame may still be waiting
2783
+ * on a block that can retire. The window is one interleave depth for a gap's
2784
+ * last block to finish arriving, one block lifetime to fail it, and one more
2785
+ * for an owed Worker cleanup that can keep a failing block pending. Every
2786
+ * term comes from the track's catalog geometry; there is no separate cap.
2787
+ */
2788
+ terminalRetentionMsForPacket(packetId: number): number {
2789
+ const config = this.#resolveTrackConfig(packetId)
2790
+ return config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)
2791
+ }
2792
+ /** Remaining fetch budget for a specific repair-requested block. */
2793
+ repairFetchTimeoutMsForBlock(
2794
+ sbn: number,
2795
+ packetId: number,
2796
+ catalogTrackName?: string,
2797
+ ): number {
2798
+ const deadlineMs = this.#activeBlockDeadlinesMs.get(
2799
+ this.#blockKey(sbn, packetId, catalogTrackName),
2800
+ )
2801
+ if (deadlineMs !== undefined) {
2802
+ return Math.max(1, Math.ceil(deadlineMs - performance.now()))
2803
+ }
2804
+ const trackConfig = this.#resolveTrackConfig(packetId)
2805
+ return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig))
2806
+ }
2807
+
2808
+ /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
2809
+ // -----------------------------------------------------------------------
2810
+ // iso-ssbg1-v1 block location (BLO-35597 iso:2/iso:3)
2811
+ // -----------------------------------------------------------------------
2812
+
2813
+ /** The configured `fec.blockProfile` of a packetId (undefined until configured). */
2814
+ blockProfileForPacket(packetId: number): FecBlockProfile | undefined {
2815
+ return this.#trackConfigs.get(packetId)?.blockProfile
2816
+ }
2817
+
2818
+ /**
2819
+ * Whether a packetId has a configured block geometry. iso-ssbg1-v1 is the
2820
+ * only profile, so every configured track has it; a packetId never
2821
+ * configured (or released) has none and gets no FEC block tracking.
2822
+ */
2823
+ #hasBlockProfile(packetId: number): boolean {
2824
+ return this.#trackConfigs.get(packetId)?.blockProfile !== undefined
2825
+ }
2826
+
2827
+ #isoLocatorFor(packetId: number, catalogTrackName?: string): IsoBlockLocator<IsoHeldSource> {
2828
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
2829
+ let locator = this.#isoLocators.get(streamKey)
2830
+ if (!locator) {
2831
+ locator = new IsoBlockLocator<IsoHeldSource>(this.kForPacket(packetId), this.#isoRetentionBlocks(packetId))
2832
+ this.#isoLocators.set(streamKey, locator)
2833
+ }
2834
+ return locator
2835
+ }
2836
+
2837
+ /**
2838
+ * The locator a call is about to grow, with its retention brought up to
2839
+ * date: the horizon follows catalog timing, which a later configuration
2840
+ * (this track's or another video track's keyframe cadence) can change.
2841
+ */
2842
+ #growingIsoLocatorFor(packetId: number, catalogTrackName?: string): IsoBlockLocator<IsoHeldSource> {
2843
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName)
2844
+ locator.retentionBlocks = this.#isoRetentionBlocks(packetId)
2845
+ return locator
2846
+ }
2847
+
2848
+ #dropIsoLocators(packetId: number): void {
2849
+ for (const key of [...this.#isoLocators.keys()]) {
2850
+ if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key)
2851
+ }
2852
+ }
2853
+
2854
+ /**
2855
+ * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
2856
+ * still hold terminal state for (`terminalRetentionMsForPacket`) over the
2857
+ * block span, plus the block being filled, measured with the shared
2858
+ * lower-bound metric so a retained block is never forgotten early. Every
2859
+ * term is the packet's catalog geometry, which configuration validated
2860
+ * (#upsertTrackConfig), so this never falls back: an underivable horizon
2861
+ * throws rather than leave the locator without retention.
2862
+ */
2863
+ #isoRetentionBlocks(packetId: number): number {
2864
+ const config = this.#trackConfigs.get(packetId)
2865
+ if (config?.blockProfile === undefined || !(config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS)) {
2866
+ throw new Error(
2867
+ `[FECManager] packetId=${packetId} has no iso-ssbg1-v1 block span to derive block-location retention from`,
2868
+ )
2869
+ }
2870
+ const blocks = Math.ceil(this.terminalRetentionMsForPacket(packetId) / config.interleaveDepthMs) + 1
2871
+ if (!Number.isSafeInteger(blocks) || blocks <= 0) {
2872
+ throw new Error(`[FECManager] packetId=${packetId} iso-ssbg1-v1 retention of ${blocks} blocks is not derivable`)
2873
+ }
2874
+ return blocks
2875
+ }
2876
+
2877
+ /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
2878
+ isoSourceFits(packetId: number, packetLength: number): boolean {
2879
+ return ssbg1FitsSymbol(packetLength, this.symbolSizeForPacket(packetId))
2880
+ }
2881
+
2882
+ /**
2883
+ * Locate an iso-ssbg1-v1 source by range membership in a block a repair
2884
+ * already stated. Null while its block is unknown: hold it (holdIsoSource).
2885
+ */
2886
+ locateIsoSource(
2887
+ packetId: number,
2888
+ catalogTrackName: string | undefined,
2889
+ ssId: number,
2890
+ ): { sbn: number; esi: number } | null {
2891
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId)
2892
+ return located === null ? null : { sbn: located.block.start, esi: located.esi }
2893
+ }
2894
+
2895
+ /**
2896
+ * Hold a first-arrival iso-ssbg1-v1 source whose block no repair has stated
2897
+ * yet. Returns false for a later copy of an SS_ID already held.
2898
+ */
2899
+ holdIsoSource(
2900
+ packetId: number,
2901
+ catalogTrackName: string | undefined,
2902
+ ssId: number,
2903
+ source: IsoHeldSource,
2904
+ ): boolean {
2905
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName)
2906
+ const evictedBefore = locator.heldEvicted
2907
+ const held = locator.hold(ssId, source)
2908
+ const evicted = locator.heldEvicted - evictedBefore
2909
+ if (evicted > 0) {
2910
+ const before = this.#isoHeldEvictedCount
2911
+ this.#isoHeldEvictedCount += evicted
2912
+ if (before < 5 || Math.floor(before / 100) !== Math.floor(this.#isoHeldEvictedCount / 100)) {
2913
+ console.warn(
2914
+ `[FECManager] packetId=${packetId} iso-ssbg1-v1 held-source cap (${locator.heldCapacity}) ` +
2915
+ `evicted ${evicted} unplaced source(s); SS_IDs are not consecutive (C.5.2)`,
2916
+ )
2917
+ }
2918
+ }
2919
+ return held
2920
+ }
2921
+
2922
+ /**
2923
+ * Apply an iso-ssbg1-v1 repair symbol's `(SS_Start, SSB_length)`: states the
2924
+ * block, and hands back the held sources it (and any repair-less span in
2925
+ * front of it) now places. The caller feeds them as first-arrival sources,
2926
+ * then the repair symbol, the order they had on the wire. A repair that
2927
+ * contradicts a known block is refused (counted) and must be dropped.
2928
+ */
2929
+ placeIsoRepair(
2930
+ packetId: number,
2931
+ catalogTrackName: string | undefined,
2932
+ ssStart: number,
2933
+ ssbLength: number,
2934
+ ): IsoRepairPlacement<IsoHeldSource> {
2935
+ const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength)
2936
+ if (placement.status !== 'placed') {
2937
+ this.#isoRepairRefusedCount++
2938
+ if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
2939
+ console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`)
2940
+ }
2941
+ return placement
2942
+ }
2943
+ // A repair-less span has no repair to state its length, so it is known
2944
+ // here: its sources make it clean exactly when all of them arrived. A
2945
+ // stated block learns its SSB_length from its own repair symbol, fed
2946
+ // after its placed sources exactly as on the wire (feedRepairSymbol).
2947
+ if (placement.span !== undefined) {
2948
+ const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName)
2949
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length)
2950
+ }
2951
+
2952
+ if (placement.span !== undefined && placement.span.placed.length === 0) {
2953
+ // Every SS_ID of the span vanished, repair included: it resolves
2954
+ // through its deadline like any vanished block.
2955
+ this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true)
2956
+ }
2957
+ return placement
2958
+ }
2959
+
2960
+ /**
2961
+ * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
2962
+ * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
2963
+ * that could hold them is pending or not yet stated by a repair, else the
2964
+ * starts of the blocks that failed or vanished.
2965
+ *
2966
+ * `untracked` reads as the release gate reads it (MmtpRouter
2967
+ * #createFecReleaseGate): a block holding either released frame's SS_ID
2968
+ * (`fromSsId` or `toSsId`) delivered that frame, so untracked there means it
2969
+ * resolved and retired; a block starting after the stream's frontier
2970
+ * (`highestSbn`, an SS_Start) may still be heard from; a block at or behind the
2971
+ * frontier that no symbol of this manager ever reached vanished, and its
2972
+ * media is lost.
2973
+ */
2974
+ isoSpanResolution(
2975
+ packetId: number,
2976
+ catalogTrackName: string | undefined,
2977
+ fromSsId: number,
2978
+ toSsId: number,
2979
+ ): readonly number[] | null {
2980
+ if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return []
2981
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))
2982
+ if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null
2983
+ const highest = this.highestSbn(packetId, catalogTrackName)
2984
+ const lost: number[] = []
2985
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
2986
+ const resolution = this.blockResolution(block.start, packetId, catalogTrackName)
2987
+ if (resolution === 'pending') return null
2988
+ if (resolution === 'failed') {
2989
+ lost.push(block.start)
2990
+ } else if (resolution === 'untracked') {
2991
+ if (
2992
+ isoBlockContains(block.start, block.length, fromSsId) ||
2993
+ isoBlockContains(block.start, block.length, toSsId)
2994
+ ) {
2995
+ continue
2996
+ }
2997
+ if (highest === undefined || serial32Precedes(highest, block.start)) return null
2998
+ lost.push(block.start)
2999
+ }
3000
+ }
3001
+ return lost
3002
+ }
3003
+
3004
+ /**
3005
+ * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
3006
+ * the sources held now for a block no repair has stated yet, and the held
3007
+ * sources the capacity cap evicted (cumulative), and the sources a
3008
+ * synchronous decoder held unplaced and retired at its horizon (cumulative).
3009
+ */
3010
+ get isoDiagnostics(): {
3011
+ repairRefused: number
3012
+ sourceOversize: number
3013
+ heldSources: number
3014
+ heldEvicted: number
3015
+ decoderUnplacedRetired: number
3016
+ decoderUnplacedRetireFailed: number
3017
+ } {
3018
+ let heldSources = 0
3019
+ for (const locator of this.#isoLocators.values()) heldSources += locator.heldCount
3020
+ return {
3021
+ repairRefused: this.#isoRepairRefusedCount,
3022
+ sourceOversize: this.#isoSourceOversizeCount,
3023
+ heldSources,
3024
+ heldEvicted: this.#isoHeldEvictedCount,
3025
+ decoderUnplacedRetired: this.#isoDecoderUnplacedRetired,
3026
+ decoderUnplacedRetireFailed: this.#isoDecoderUnplacedRetireFailed,
3027
+ }
3028
+ }
3029
+
3030
+ isTrackConfigured(packetId: number): boolean {
3031
+ return this.#trackConfigs.has(packetId)
3032
+ }
3033
+
3034
+ /** Catalog/reset epoch of a packet's streams; gap decisions carry it. */
3035
+ epochFor(packetId: number): number {
3036
+ return this.#packetEpochs.get(packetId) ?? 0
3037
+ }
3038
+
3039
+ /** Configured media kind of a packetId, when known. */
3040
+ trackKindFor(packetId: number): TrackKind | undefined {
3041
+ return this.#trackConfigs.get(packetId)?.trackKind
3042
+ }
3043
+
3044
+ /** Configured codec of a packetId, when known. */
3045
+ codecFor(packetId: number): string | undefined {
3046
+ return this.#trackConfigs.get(packetId)?.codec
3047
+ }
3048
+
3049
+ /**
3050
+ * Block classifier geometry of one stream: its own stream-scoped geometry,
3051
+ * else the packet's (fail-closed when absent, or when a sibling stream of
3052
+ * the packet has its own geometry and this one has none).
3053
+ */
3054
+ geometryFor(packetId: number, catalogTrackName?: string): BlockClassifierGeometry {
3055
+ return this.#geometryFor(packetId, catalogTrackName)
3056
+ }
3057
+
3058
+ /** Current classifier mode of a stream. */
3059
+ classifierModeFor(
3060
+ packetId: number,
3061
+ catalogTrackName?: string,
3062
+ ): { mode: ClassifierMode; reason: ClassifierReason | null } {
3063
+ const classifier = this.#classifierFor(packetId, catalogTrackName)
3064
+ return { mode: classifier.mode, reason: classifier.reason }
3065
+ }
3066
+
3067
+ /**
3068
+ * Whether an MPU boundary still bounds this stream's RAPs (see
3069
+ * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
3070
+ * it does not. A stream with no classifier yet has shown nothing against it.
3071
+ */
3072
+ mpuBoundsRapsFor(packetId: number, catalogTrackName?: string): boolean {
3073
+ return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true
3074
+ }
3075
+
3076
+ /** A block's class now, or frozen at its resolution. */
3077
+ blockClassFor(sbn: number, packetId: number, catalogTrackName?: string): BlockClass {
3078
+ const frozen = this.#resolvedBlockClasses.get(this.#blockKey(sbn, packetId, catalogTrackName))
3079
+ if (frozen !== undefined) return frozen
3080
+ return this.#peekClass(sbn, packetId, catalogTrackName)
3081
+ }
3082
+
3083
+ /**
3084
+ * Lifecycle resolution of one block for in-order frame release: `pending`
3085
+ * while it can still complete, `complete`/`failed` once terminal, and
3086
+ * `untracked` when no symbol of it was ever accepted.
3087
+ */
3088
+ blockResolution(sbn: number, packetId: number, catalogTrackName?: string): FecBlockResolution {
3089
+ return this.#blockResolutionFor(this.#blockKey(sbn, packetId, catalogTrackName))
3090
+ }
3091
+
3092
+ /** Highest SBN any symbol of this stream carried in the current epoch. */
3093
+ highestSbn(packetId: number, catalogTrackName?: string): number | undefined {
3094
+ return this.#highestSbn.get(this.#streamKey(packetId, catalogTrackName))?.sbn
3095
+ }
3096
+
3097
+ /**
3098
+ * Record a RAP frame released in order, for the classifier's RAP-spacing
3099
+ * invariant (consecutive MPUs exactly one keyframe interval apart).
3100
+ */
3101
+ noteReleasedRap(
3102
+ packetId: number,
3103
+ catalogTrackName: string | undefined,
3104
+ mpu: number,
3105
+ presentationTime: bigint,
3106
+ mediaTimescale: number,
3107
+ ): void {
3108
+ if (!this.#trackConfigs.has(packetId)) return
3109
+ this.#applyClassifierChanges(
3110
+ packetId,
3111
+ catalogTrackName,
3112
+ this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
3113
+ mpu,
3114
+ presentationTime,
3115
+ mediaTimescale,
3116
+ ),
3117
+ )
3118
+ }
3119
+
3120
+ // -----------------------------------------------------------------------
3121
+ // Configuration
3122
+ // -----------------------------------------------------------------------
3123
+
3124
+ /** Configure FEC parameters. */
3125
+ configure(config: FECManagerConfig): void {
3126
+ if (config.k != null) this.#fecK = config.k
3127
+ if (config.symbolSize != null && config.symbolSize > 0) this.#fecSymbolSize = config.symbolSize
3128
+ if (config.interleaveDepthMs != null) this.#fecInterleaveDepthMs = config.interleaveDepthMs
3129
+ if (config.fps != null && Number.isFinite(config.fps) && config.fps > 0) {
3130
+ this.#fecFps = config.fps
3131
+ }
3132
+ // interleaveDepthMs is in milliseconds per spec §5.1.
3133
+ // Valid range: 33ms (interactive/gaming) to 10000ms (broadcast ATSC 3.0).
3134
+ // Warn if value looks like frame count instead of ms (common misconfiguration).
3135
+ if (config.interleaveDepthMs != null && config.interleaveDepthMs > 0 && config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS) {
3136
+ console.warn(`[FECManager] interleaveDepthMs=${config.interleaveDepthMs} looks like frame count, not milliseconds (§5.1 requires ms). Expected range: ${MIN_INTERLEAVE_DEPTH_MS}-10000ms.`)
3137
+ }
3138
+ if (config.timeoutMs != null && config.timeoutMs > 0) {
3139
+ this.#fecTimeoutMs = config.timeoutMs
3140
+ } else if (
3141
+ config.interleaveDepthMs != null &&
3142
+ config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS
3143
+ ) {
3144
+ this.#fecTimeoutMs = computeFecDeliveryWindowMs({
3145
+ interleaveDepthMs: config.interleaveDepthMs,
3146
+ sourceSymbols: this.#fecK,
3147
+ symbolSize: this.#fecSymbolSize,
3148
+ mediaUnitsPerSecond: config.fps,
3149
+ })
3150
+ }
3151
+ // A shared multicast parser receives every packetId. Keep existing track
3152
+ // deadlines at least as wide as the selected video delivery envelope so a
3153
+ // short audio interleave cannot expire during browser/AMT scheduling gaps.
3154
+ for (const [packetId, track] of this.#trackConfigs) {
3155
+ if (track.timeoutMs < this.#fecTimeoutMs) {
3156
+ this.#trackConfigs.set(packetId, { ...track, timeoutMs: this.#fecTimeoutMs })
3157
+ }
3158
+ }
3159
+ }
3160
+
3161
+ /**
3162
+ * Configure FEC parameters for one packetId without changing legacy
3163
+ * defaults. With `catalogTrackName`, `config.geometry` is that stream's
3164
+ * own classifier geometry (ABR rungs that share a packetId each get
3165
+ * theirs); K, T, timing, kind and codec stay per packetId.
3166
+ */
3167
+ configureTrack(packetId: number, config: FECManagerConfig, catalogTrackName?: string): void {
3168
+ this.#upsertTrackConfig(packetId, config, catalogTrackName)
3169
+ }
3170
+
3171
+ /** Register a FEC decoder for a specific packetId (track). */
3172
+ setFecDecoder(
3173
+ packetId: number,
3174
+ client: WasmFecDecoder,
3175
+ k: number,
3176
+ config?: FECManagerConfig,
3177
+ catalogTrackName?: string,
3178
+ ): void {
3179
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3180
+ this.#assertExclusiveDecoderClient(
3181
+ streamKey,
3182
+ client,
3183
+ [...this.#fecDecoders].map(([key, entry]) => [key, entry.client] as const),
3184
+ 'decoder',
3185
+ )
3186
+ const trackConfig = this.#upsertTrackConfig(packetId, { ...config, k }, catalogTrackName)
3187
+ this.#fecDecoders.set(streamKey, { client, k: trackConfig.k })
3188
+ }
3189
+
3190
+ /**
3191
+ * Register a Worker-backed FEC decoder for a specific packetId (track).
3192
+ *
3193
+ * Worker-backed tracks decode asynchronously — feedSourceSymbol/feedRepairSymbol
3194
+ * return null immediately, and recovered frames arrive via the onBlockRecovered callback.
3195
+ *
3196
+ * Takes precedence over sync WASM decoders for the same packetId.
3197
+ */
3198
+ setFecWorker(
3199
+ packetId: number,
3200
+ client: FecWorkerClient,
3201
+ config: FECManagerConfig,
3202
+ catalogTrackName?: string,
3203
+ ): void {
3204
+ const k = config?.k
3205
+ if (k === undefined || !Number.isFinite(k) || k <= 0) {
3206
+ throw new Error(`[FECManager] packetId=${packetId} Worker requires an explicit positive k`)
3207
+ }
3208
+ const symbolSize = config.symbolSize
3209
+ if (symbolSize === undefined || !Number.isFinite(symbolSize) || symbolSize <= 0) {
3210
+ throw new Error(
3211
+ `[FECManager] packetId=${packetId} Worker requires an explicit positive symbolSize`,
3212
+ )
3213
+ }
3214
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3215
+ this.#assertExclusiveDecoderClient(
3216
+ streamKey,
3217
+ client,
3218
+ this.#workerClients,
3219
+ 'worker',
3220
+ )
3221
+ // Every Worker leaves routing through #retireWorker, which fails the
3222
+ // blocks it still owed and reports the stream's decoder unavailable.
3223
+ // Overwriting a registration would skip that path and strand those
3224
+ // blocks, so a second Worker under a routed stream is refused.
3225
+ const incumbent = this.#workerClients.get(streamKey)
3226
+ if (incumbent !== undefined && incumbent !== client) {
3227
+ throw new Error(
3228
+ `[FECManager] stream ${streamKey} already routes to a Worker; ` +
3229
+ `call clearFecWorker before registering another`,
3230
+ )
3231
+ }
3232
+ if (config) this.#upsertTrackConfig(packetId, config, catalogTrackName)
3233
+ const workerK = this.#resolveTrackConfig(packetId).k
3234
+ this.#workerClients.set(streamKey, client)
3235
+ this.#releasedWorkerClients.delete(client)
3236
+
3237
+ client.onFrame((data: ArrayBuffer, meta: FrameMeta) => {
3238
+ if (this.#releasedWorkerClients.has(client)) return
3239
+ if (meta.recovered) {
3240
+ // Recovered Worker events represent one exact source-symbol position.
3241
+ // Block-completion accounting needs that exact ESI, and counting an
3242
+ // ESI-less event as recovered would report healthy FEC while dropping
3243
+ // the media. Enforce the Worker contract before any recovery metric.
3244
+ // The Worker names the recovered block's authored SSB_length; ESIs
3245
+ // at or past it are not source symbols of the block and are never
3246
+ // emitted.
3247
+ if (
3248
+ !Number.isInteger(meta.ssbLength) ||
3249
+ meta.ssbLength! <= 0 ||
3250
+ meta.ssbLength! > workerK
3251
+ ) {
3252
+ const kind: FecWorkerErrorCode = 'recovered-symbol-ssb-length-invalid'
3253
+ const seen = this.#workerErrorCounts.get(kind) ?? 0
3254
+ this.#workerErrorCounts.set(kind, seen + 1)
3255
+ if (seen < WORKER_ERROR_LOG_CAP) {
3256
+ console.warn(
3257
+ `[FECManager] Dropping recovered symbol with invalid SSB_length: pid=${packetId} sbn=${meta.sbn} ssbLength=${String(meta.ssbLength)}`,
3258
+ )
3259
+ }
3260
+ return
3261
+ }
3262
+ if (
3263
+ !Number.isInteger(meta.esi) ||
3264
+ meta.esi! < 0 ||
3265
+ meta.esi! >= meta.ssbLength!
3266
+ ) {
3267
+ const kind = 'recovered-symbol-missing-esi'
3268
+ const seen = this.#workerErrorCounts.get(kind) ?? 0
3269
+ this.#workerErrorCounts.set(kind, seen + 1)
3270
+ if (seen < WORKER_ERROR_LOG_CAP) {
3271
+ console.warn(
3272
+ `[FECManager] Dropping recovered symbol without valid ESI: pid=${packetId} sbn=${meta.sbn} esi=${String(meta.esi)} ssbLength=${String(meta.ssbLength)}`,
3273
+ )
3274
+ }
3275
+ return
3276
+ }
3277
+ const esi = meta.esi!
3278
+
3279
+ // Suppress duplicate routing when the worker fires recovered=true
3280
+ // for a block ALREADY CLEANLY COMPLETED by K source symbols.
3281
+ //
3282
+ // BLO-3323 L15: predicate was previously `#completedBlocks.has(sbn)`,
3283
+ // but `#completedBlocks` is populated by 5 paths (clean K-arrival,
3284
+ // failed timeout, every worker frame emit via markBlockCompleted below,
3285
+ // external markBlockCompleted, and cancelBlockTimeout). The first
3286
+ // worker frame for a block adds the SBN, so subsequent recovered=true
3287
+ // emits for the same block were always suppressed → blocksRecovered
3288
+ // stayed at 0 even when recovery actually fired. Switching to the
3289
+ // narrower #cleanlyCompletedBlocks set (populated only by trackBlock
3290
+ // when count >= K) preserves the original dedup intent (BLO-3035
3291
+ // layer 4 — don't double-route a block already received via source)
3292
+ // while letting genuinely-recovered blocks bump the counter.
3293
+ const recoveredCatalogTrackName = catalogTrackName
3294
+ ?? this.#decoderBlockCatalogTrackName(client, meta.sbn)
3295
+ if (!this.#claimDecoderBlock(client, meta.sbn, recoveredCatalogTrackName)) return
3296
+ const blockKey = this.#blockKey(meta.sbn, packetId, recoveredCatalogTrackName)
3297
+ const cleanlyCompleted = this.#cleanlyCompletedBlocks.has(blockKey)
3298
+ if (!cleanlyCompleted) {
3299
+ if (!this.#workerRecoveredBlocks.has(blockKey)) {
3300
+ this.#traceLifecycle(
3301
+ 'recovered',
3302
+ meta.sbn,
3303
+ packetId,
3304
+ recoveredCatalogTrackName,
3305
+ )
3306
+ this.#workerRecoveredBlocks.add(blockKey)
3307
+ this.#fecStats.blocksRecovered++
3308
+ this.#statsForPacket(packetId).blocksRecovered++
3309
+ if (this.#workerRecoveredBlocks.size > 1000) {
3310
+ dropOldest(this.#workerRecoveredBlocks, 500)
3311
+ }
3312
+ this.#noteBlockRepaired(blockKey, meta.sbn, packetId, recoveredCatalogTrackName)
3313
+ }
3314
+
3315
+ // RaptorQ returns the full K-symbol block, not only erased symbols.
3316
+ // The direct path already parsed every source ESI in #seenSymbols;
3317
+ // routing those symbols again injects duplicate MFU fragments and can
3318
+ // leave a real FI=3 tail followed by duplicate FI=2 fragments.
3319
+ const symbolKey = `${blockKey}:${esi}`
3320
+ if (!this.#seenSymbols.has(symbolKey)) {
3321
+ this.#seenSymbols.add(symbolKey)
3322
+ this.onBlockRecovered?.(
3323
+ meta.sbn,
3324
+ packetId,
3325
+ data,
3326
+ meta,
3327
+ recoveredCatalogTrackName,
3328
+ )
3329
+ }
3330
+ }
3331
+
3332
+ // The worker emits recovered source symbols in ESI order. Complete the
3333
+ // block only after its final authored slot so assemblers receive every
3334
+ // missing symbol before their completion callback flushes buffered media.
3335
+ if (
3336
+ esi >= meta.ssbLength! - 1 &&
3337
+ !this.#completedBlocks.has(blockKey)
3338
+ ) {
3339
+ this.cancelBlockTimeout(meta.sbn, packetId, recoveredCatalogTrackName)
3340
+ if (recoveredCatalogTrackName === undefined) {
3341
+ this.onBlockComplete?.(meta.sbn, packetId)
3342
+ } else {
3343
+ this.onBlockComplete?.(
3344
+ meta.sbn,
3345
+ packetId,
3346
+ recoveredCatalogTrackName,
3347
+ )
3348
+ }
3349
+ }
3350
+ } else {
3351
+ const completedCatalogTrackName = catalogTrackName
3352
+ ?? this.#decoderBlockCatalogTrackName(client, meta.sbn)
3353
+ this.markBlockCompleted(meta.sbn, packetId, completedCatalogTrackName)
3354
+ }
3355
+ })
3356
+
3357
+ client.onSnapshot((stats: FecTrackStats) => {
3358
+ if (this.#releasedWorkerClients.has(client)) return
3359
+ this.#fecWorkerStats.set(packetId, stats)
3360
+ try {
3361
+ this.onFecStatsUpdate?.(packetId, stats)
3362
+ } catch (error) {
3363
+ console.warn('[FECManager] FEC stats callback failed:', error)
3364
+ }
3365
+ for (const observer of this.#fecStatsObservers) {
3366
+ try {
3367
+ observer(packetId, stats)
3368
+ } catch (error) {
3369
+ console.warn('[FECManager] FEC stats observer failed:', error)
3370
+ }
3371
+ }
3372
+ })
3373
+
3374
+ client.onCleanupComplete((sbn: number) => {
3375
+ if (this.#releasedWorkerClients.has(client)) return
3376
+ const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
3377
+ const block = this.#parseBlockKey(key)
3378
+ return block.packetId === packetId &&
3379
+ block.sbn === sbn &&
3380
+ this.#pendingWorkerCleanupClients.get(key) === client
3381
+ })
3382
+ for (const key of cleanupKeys) this.#settleOwedCleanup(key, 'cleanup-ack')
3383
+ })
3384
+
3385
+ client.onError((msg: string, code?: FecWorkerErrorCode) => {
3386
+ const requestedKind = code ?? msg
3387
+ const kind =
3388
+ this.#workerErrorCounts.has(requestedKind) ||
3389
+ this.#workerErrorCounts.size < WORKER_ERROR_KIND_CAP - 1
3390
+ ? requestedKind
3391
+ : WORKER_ERROR_OVERFLOW_KIND
3392
+ const seen = this.#workerErrorCounts.get(kind) ?? 0
3393
+ this.#workerErrorCounts.set(kind, seen + 1)
3394
+ if (seen < WORKER_ERROR_LOG_CAP) {
3395
+ console.warn('[FECManager] Worker error:', msg)
3396
+ } else if (seen === WORKER_ERROR_LOG_CAP) {
3397
+ console.warn(
3398
+ `[FECManager] Worker error (suppressing further copies of ${kind}): ${msg}`,
3399
+ )
3400
+ }
3401
+ })
3402
+ }
3403
+
3404
+ /**
3405
+ * Remove a stream's Worker decoder from routing.
3406
+ *
3407
+ * Returns false when no Worker is registered under that exact stream key.
3408
+ * On success every cleanup acknowledgement still owed by the client is
3409
+ * resolved by failing its block now (a Worker that is going away cannot
3410
+ * post it), the client's block ownership is released, and
3411
+ * onDecoderUnavailable fires once with reason 'cleared' and the decoder
3412
+ * that remains for the stream ('sync' or 'none'). Call this before
3413
+ * disposing the client; a client disposed while still registered is
3414
+ * evicted on its next symbol or reset with reason 'disposed'.
3415
+ */
3416
+ clearFecWorker(packetId: number, catalogTrackName?: string): boolean {
3417
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3418
+ const client = this.#workerClients.get(streamKey)
3419
+ if (!client) return false
3420
+ this.#retireWorker(streamKey, client, 'cleared')
3421
+ return true
3422
+ }
3423
+
3424
+ /**
3425
+ * Take a Worker client out of routing under one stream key, fail the blocks
3426
+ * whose completion it still owed, and report the stream's decoder
3427
+ * unavailable together with whatever still decodes the stream.
3428
+ */
3429
+ #retireWorker(streamKey: string, client: FecWorkerClient, reason: FecDecoderUnavailableReason): void {
3430
+ this.#workerClients.delete(streamKey)
3431
+ this.#releaseWorkerClient(client)
3432
+ this.#decoderUnavailableEvents++
3433
+ const stream = this.#parseStreamKey(streamKey)
3434
+ const fallbackDecoder: FecFallbackDecoder =
3435
+ this.#decoderForPacket(stream.packetId, stream.catalogTrackName) ? 'sync' : 'none'
3436
+ this.onDecoderUnavailable?.({
3437
+ packetId: stream.packetId,
3438
+ ...(stream.catalogTrackName === undefined ? {} : { catalogTrackName: stream.catalogTrackName }),
3439
+ reason,
3440
+ fallbackDecoder,
3441
+ })
3442
+ }
3443
+
3444
+ /**
3445
+ * Fail every block whose Worker cleanup acknowledgement is owed by `client`
3446
+ * and drop its block ownership, so no block waits on a message the Worker
3447
+ * will never post.
3448
+ */
3449
+ #releaseWorkerClient(client: FecWorkerClient): void {
3450
+ const owed = [...this.#pendingWorkerCleanupClients]
3451
+ .filter(([, owner]) => owner === client)
3452
+ .map(([key]) => key)
3453
+ for (const key of owed) this.#settleOwedCleanup(key, 'decoder-unavailable')
3454
+ this.#decoderBlockOwners.delete(client)
3455
+ }
3456
+
3457
+ /**
3458
+ * Bound the wait for one Worker cleanup acknowledgement by the block's
3459
+ * catalog-derived terminal lifetime. When it elapses with the cleanup still
3460
+ * owed to the same client, the block fails as if the ack had arrived: its
3461
+ * fail deadline already passed, so failing it is the decision that deadline
3462
+ * made. A late ack then finds nothing owed and is a no-op.
3463
+ */
3464
+ #boundOwedCleanup(key: string, packetId: number, client: FecWorkerClient): void {
3465
+ this.#clearOwedCleanupBound(key)
3466
+ const bound = {
3467
+ handle: setTimeout(() => {
3468
+ if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return
3469
+ this.#pendingWorkerCleanupBounds.delete(key)
3470
+ if (
3471
+ !this.#pendingWorkerCleanups.has(key) ||
3472
+ this.#pendingWorkerCleanupClients.get(key) !== client
3473
+ ) {
3474
+ return
3475
+ }
3476
+ this.#settleOwedCleanup(key, 'cleanup-ack-timeout')
3477
+ }, Math.ceil(this.#liveBlockLifetimeMs(this.#resolveTrackConfig(packetId)))),
3478
+ }
3479
+ this.#pendingWorkerCleanupBounds.set(key, bound)
3480
+ }
3481
+
3482
+ #clearOwedCleanupBound(key: string): void {
3483
+ const bound = this.#pendingWorkerCleanupBounds.get(key)
3484
+ if (!bound) return
3485
+ clearTimeout(bound.handle)
3486
+ this.#pendingWorkerCleanupBounds.delete(key)
3487
+ }
3488
+
3489
+ /**
3490
+ * Resolve one owed Worker cleanup: drop the pending entry and fail the block
3491
+ * unless it already completed. Shared by the cleanup acknowledgement and by
3492
+ * Worker retirement, so the two paths cannot drift in their bookkeeping.
3493
+ */
3494
+ #settleOwedCleanup(
3495
+ key: string,
3496
+ event: 'cleanup-ack' | 'cleanup-ack-timeout' | 'decoder-unavailable',
3497
+ ): void {
3498
+ this.#clearOwedCleanupBound(key)
3499
+ this.#pendingWorkerCleanups.delete(key)
3500
+ this.#pendingWorkerCleanupClients.delete(key)
3501
+ if (this.#completedBlocks.has(key)) return
3502
+ const block = this.#parseBlockKey(key)
3503
+ this.#traceLifecycle(event, block.sbn, block.packetId, block.catalogTrackName)
3504
+ this.#failBlock(block.sbn, block.packetId, block.catalogTrackName)
3505
+ }
3506
+
3507
+ /** Evict a disposed client under every stream key that still maps to it. */
3508
+ #evictDisposedWorker(client: FecWorkerClient): void {
3509
+ for (const [key, registered] of [...this.#workerClients]) {
3510
+ if (registered !== client) continue
3511
+ const stream = this.#parseStreamKey(key)
3512
+ const track = stream.catalogTrackName === undefined ? '' : ` track=${stream.catalogTrackName}`
3513
+ console.warn(
3514
+ `[FECManager] packetId=${stream.packetId}${track} Worker decoder was disposed while still registered; evicting it`,
3515
+ )
3516
+ this.#retireWorker(key, client, 'disposed')
3517
+ }
3518
+ }
3519
+
3520
+ /** Called by player when framerate is known (from decoder output). Refines FEC block timeout. */
3521
+ setFramerate(fps: number): void {
3522
+ if (this.#fpsDetected || fps <= 0) return
3523
+ this.#fpsDetected = true
3524
+ this.#fecFps = fps
3525
+ // Only a valid §5.1 ms interleave refines the timeout; a sub-floor value is
3526
+ // a raw frame count and would collapse it (see MIN_INTERLEAVE_DEPTH_MS).
3527
+ if (this.#fecInterleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
3528
+ this.#fecTimeoutMs = computeFecDeliveryWindowMs({
3529
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
3530
+ sourceSymbols: this.#fecK,
3531
+ symbolSize: this.#fecSymbolSize,
3532
+ mediaUnitsPerSecond: fps,
3533
+ })
3534
+ }
3535
+ for (const [packetId, config] of this.#trackConfigs) {
3536
+ if (config.fps !== undefined || config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS) continue
3537
+ this.#trackConfigs.set(packetId, {
3538
+ ...config,
3539
+ fps,
3540
+ timeoutMs: Math.max(
3541
+ this.#fecTimeoutMs,
3542
+ computeFecDeliveryWindowMs({
3543
+ interleaveDepthMs: config.interleaveDepthMs,
3544
+ sourceSymbols: config.k,
3545
+ symbolSize: config.symbolSize,
3546
+ mediaUnitsPerSecond: fps,
3547
+ }),
3548
+ ),
3549
+ })
3550
+ }
3551
+ }
3552
+
3553
+ // -----------------------------------------------------------------------
3554
+ // Symbol feeding (codec-agnostic)
3555
+ // -----------------------------------------------------------------------
3556
+
3557
+ /**
3558
+ * Feed a source symbol to the WASM FEC decoder.
3559
+ *
3560
+ * Does NOT track block source counts or fire lifecycle events — call
3561
+ * `trackBlock()` separately BEFORE this method (MmtpRouter does this).
3562
+ *
3563
+ * @returns Recovered block data if WASM completed the block, else null.
3564
+ * Caller is responsible for routing recovered data and updating
3565
+ * block completion state via `markBlockCompleted()`.
3566
+ */
3567
+ feedSourceSymbol(
3568
+ packetId: number,
3569
+ ssId: number,
3570
+ symbolData: Uint8Array,
3571
+ alta?: { auth: Uint8Array; payloadEnd: number },
3572
+ catalogTrackName?: string,
3573
+ ): Uint8Array | null {
3574
+ this.#fecStats.sourcePackets++
3575
+ this.#statsForPacket(packetId).sourcePackets++
3576
+ // A packetId with no configured block profile has no block geometry and
3577
+ // no decoder (setFecDecoder/setFecWorker configure the track): nothing to
3578
+ // decode.
3579
+ if (!this.#hasBlockProfile(packetId)) return null
3580
+ // The decoder builds the ssbg_mode1 symbol from the exact protected
3581
+ // packet, so the packet travels unpadded. Its block must already be
3582
+ // stated (MmtpRouter holds a source until a repair places it).
3583
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName)
3584
+ const located = locator.locate(ssId)
3585
+ if (located === null) {
3586
+ throw new Error(
3587
+ `[FECManager] iso-ssbg1-v1 source SS_ID=${ssId} (packetId=${packetId}) has no stated block; ` +
3588
+ 'hold it until a repair places it (placeIsoRepair)',
3589
+ )
3590
+ }
3591
+ locator.observe(ssId)
3592
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.symbolSizeForPacket(packetId))) {
3593
+ this.#isoSourceOversizeCount++
3594
+ return null
3595
+ }
3596
+ const sbn = located.block.start
3597
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName)
3598
+ const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey)
3599
+
3600
+ // Worker-backed track: dispatch async, return null (recovery via onFrame callback)
3601
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName)
3602
+ if (workerClient && !syncBlockOwner) {
3603
+ if (!this.#claimDecoderBlock(workerClient, sbn, catalogTrackName)) return null
3604
+ // Transfer an ArrayBuffer nothing else references. The source travels
3605
+ // unpadded, and a caller's buffer may be a view into a larger packet,
3606
+ // so it is copied first (T-03-06).
3607
+ const buf = symbolData.buffer.slice(
3608
+ symbolData.byteOffset,
3609
+ symbolData.byteOffset + symbolData.byteLength,
3610
+ ) as ArrayBuffer
3611
+ // Pass the flat SS_ID through to the worker. The WASM decoder places
3612
+ // the source in its block by SS_ID (ISO 23008-1 §C.5.2); the WASM add_source
3613
+ // signature is (ss_id, data, timestamp) — pre-computing sbn/esi on this
3614
+ // side produces wrong WASM argument alignment and silently breaks
3615
+ // block assembly.
3616
+ if (alta) {
3617
+ // Copy auth into a fresh ArrayBuffer to transfer zero-copy. The
3618
+ // underlying buffer of the parsed trailer view belongs to the wire
3619
+ // packet, which may be transferred separately or reused.
3620
+ const authBuf = alta.auth.buffer.slice(
3621
+ alta.auth.byteOffset,
3622
+ alta.auth.byteOffset + alta.auth.byteLength,
3623
+ ) as ArrayBuffer
3624
+ workerClient.feedSource(ssId, buf, performance.now(), {
3625
+ auth: authBuf,
3626
+ payloadEnd: alta.payloadEnd,
3627
+ })
3628
+ } else {
3629
+ workerClient.feedSource(ssId, buf, performance.now())
3630
+ }
3631
+ return null
3632
+ }
3633
+
3634
+ // Synchronous WASM path.
3635
+ const entry = this.#decoderForPacket(packetId, catalogTrackName)
3636
+ const client = syncBlockOwner ?? entry?.client
3637
+ if (!client) return null
3638
+ if (!this.#claimDecoderBlock(client, sbn, catalogTrackName)) return null
3639
+ this.#syncDecoderBlockOwners.set(blockKey, client)
3640
+
3641
+ let recovered: Uint8Array | null = null
3642
+ try {
3643
+ recovered = client.add_source(ssId, symbolData, performance.now())
3644
+ } catch {
3645
+ // WASM RefCell panic — decoder instance shared with multicast repair path
3646
+ }
3647
+ this.#retireIsoUnplaced(client, packetId, catalogTrackName)
3648
+ if (recovered || this.#completedBlocks.has(blockKey)) {
3649
+ this.#syncDecoderBlockOwners.delete(blockKey)
3650
+ }
3651
+
3652
+ return recovered
3653
+ }
3654
+
3655
+ /**
3656
+ * Feed a repair symbol to the WASM FEC decoder.
3657
+ *
3658
+ * @returns Recovered block data if repair completed the block, else null.
3659
+ * Caller is responsible for routing recovered data and updating
3660
+ * block completion state via `markBlockCompleted()`.
3661
+ */
3662
+ feedRepairSymbol(
3663
+ packetId: number,
3664
+ ssStart: number,
3665
+ ssbLength: number,
3666
+ rsId: number,
3667
+ repairData: Uint8Array,
3668
+ catalogTrackName?: string,
3669
+ ): Uint8Array | null {
3670
+ this.#fecStats.repairPackets++
3671
+ this.#statsForPacket(packetId).repairPackets++
3672
+ // A packetId with no configured block profile has no block geometry: its
3673
+ // repair names no block this manager can track or decode.
3674
+ if (!this.#hasBlockProfile(packetId)) return null
3675
+ const symbolSize = this.symbolSizeForPacket(packetId)
3676
+ if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
3677
+ this.#repairSymbolSizeMismatchCount++
3678
+ if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
3679
+ console.warn(
3680
+ `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`,
3681
+ )
3682
+ }
3683
+ return null
3684
+ }
3685
+ const fecData = repairData
3686
+
3687
+ // ISO/IEC 23008-1 C.5.3: the block is [SS_Start, SS_Start + SSB_length),
3688
+ // K' = SSB_length, and the catalog K is only its maximum. The block is
3689
+ // keyed by its SS_Start. MmtpRouter placed the block before feeding its
3690
+ // repair (placeIsoRepair). Keep the wire tuple unchanged when calling the
3691
+ // decoder below.
3692
+ const k = this.kForPacket(packetId)
3693
+ const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart)
3694
+ if (ssbLength <= 0 || ssbLength > k || block === undefined || block.span || block.length !== ssbLength) {
3695
+ return null
3696
+ }
3697
+ const sbn = ssStart
3698
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, 'repair')
3699
+
3700
+ // Repair symbols are block activity: refresh the inactivity fail bound so
3701
+ // a block being actively repaired over MoQ is not failed mid-recovery.
3702
+ // The multicast in-band path already does this at the router; this covers
3703
+ // the MoQ backfill path, which bypasses the router's packet accounting.
3704
+ this.noteBlockActivity(sbn, packetId, catalogTrackName)
3705
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName)
3706
+ if (this.#completedBlocks.has(blockKey)) return null
3707
+ if (!this.#noteAuthoredLength(blockKey, sbn, packetId, ssbLength, catalogTrackName)) {
3708
+ return null
3709
+ }
3710
+ let repairIds = this.#blockRepairRsIds.get(blockKey)
3711
+ if (!repairIds) {
3712
+ repairIds = new Set()
3713
+ this.#blockRepairRsIds.set(blockKey, repairIds)
3714
+ }
3715
+ repairIds.add(rsId)
3716
+ if (this.#repairRequestedBlocks.has(blockKey)) {
3717
+ this.#traceLifecycle('repair-arrived', sbn, packetId, catalogTrackName, rsId)
3718
+ }
3719
+
3720
+ // Every authored source symbol already arrived: the block is clean now
3721
+ // that its SSB_length is known. The decoder still receives the repair so
3722
+ // it retires its own copy of the block, but whatever it returns is the
3723
+ // source the direct path already routed, not a recovery.
3724
+ const cleanOnArrival =
3725
+ (this.#blockSourceCounts.get(blockKey) ?? 0) >= ssbLength
3726
+ const recovered = this.#dispatchRepairSymbol(
3727
+ blockKey,
3728
+ sbn,
3729
+ packetId,
3730
+ ssStart,
3731
+ ssbLength,
3732
+ rsId,
3733
+ fecData,
3734
+ catalogTrackName,
3735
+ )
3736
+ if (cleanOnArrival) {
3737
+ this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName)
3738
+ return null
3739
+ }
3740
+ return recovered
3741
+ }
3742
+
3743
+ /**
3744
+ * Record a block's authored SSB_length from a repair symbol. Returns false,
3745
+ * leaving the block unchanged, when the symbol contradicts the block: a
3746
+ * different SSB_length than an earlier repair symbol declared is dropped,
3747
+ * and an SSB_length that places an already-received source ESI at or past
3748
+ * the block's end fails the block, since its geometry can no longer be
3749
+ * trusted.
3750
+ */
3751
+ #noteAuthoredLength(
3752
+ blockKey: string,
3753
+ sbn: number,
3754
+ packetId: number,
3755
+ ssbLength: number,
3756
+ catalogTrackName?: string,
3757
+ ): boolean {
3758
+ const known = this.#blockAuthoredLengths.get(blockKey)
3759
+ if (known === ssbLength) return true
3760
+ if (known !== undefined) {
3761
+ this.#ssbLengthConflictCount++
3762
+ if (this.#ssbLengthConflictCount <= 5 || this.#ssbLengthConflictCount % 100 === 0) {
3763
+ console.warn(
3764
+ `[FECManager] Dropping repair symbol whose SSB_length ${ssbLength} conflicts with ${known} for packetId=${packetId} sbn=${sbn}`,
3765
+ )
3766
+ }
3767
+ return false
3768
+ }
3769
+ const sourceEsis = this.#blockSourceEsis.get(blockKey)
3770
+ if (sourceEsis && [...sourceEsis].some((esi) => esi >= ssbLength)) {
3771
+ this.#failBlock(sbn, packetId, catalogTrackName)
3772
+ return false
3773
+ }
3774
+ this.#blockAuthoredLengths.set(blockKey, ssbLength)
3775
+ return true
3776
+ }
3777
+
3778
+ #dispatchRepairSymbol(
3779
+ blockKey: string,
3780
+ sbn: number,
3781
+ packetId: number,
3782
+ ssStart: number,
3783
+ ssbLength: number,
3784
+ rsId: number,
3785
+ fecData: Uint8Array,
3786
+ catalogTrackName?: string,
3787
+ ): Uint8Array | null {
3788
+ const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey)
3789
+ // Worker-backed track: dispatch async, return null (recovery via onFrame callback)
3790
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName)
3791
+ if (workerClient && !syncBlockOwner) {
3792
+ if (!this.#claimDecoderBlock(workerClient, sbn, catalogTrackName)) return null
3793
+ // Create clean ArrayBuffer copy (T-03-06)
3794
+ const buf = fecData.buffer.slice(
3795
+ fecData.byteOffset,
3796
+ fecData.byteOffset + fecData.byteLength,
3797
+ ) as ArrayBuffer
3798
+ // Forward the wire-level Repair FEC Payload ID (ISO 23008-1 §C.5.3)
3799
+ // directly. WASM add_repair signature is
3800
+ // (ss_start, ssb_length, rs_id, data, timestamp) — pre-computing
3801
+ // (sbn, esi) on this side misaligns WASM args and produces 0% recovery.
3802
+ workerClient.feedRepair(ssStart, ssbLength, rsId, buf, performance.now())
3803
+ return null
3804
+ }
3805
+
3806
+ // Synchronous WASM path.
3807
+ const entry = this.#decoderForPacket(packetId, catalogTrackName)
3808
+ const client = syncBlockOwner ?? entry?.client
3809
+ if (!client) return null
3810
+ if (!this.#claimDecoderBlock(client, sbn, catalogTrackName)) return null
3811
+ this.#syncDecoderBlockOwners.set(blockKey, client)
3812
+
3813
+ let recovered: Uint8Array | null = null
3814
+ try {
3815
+ recovered = client.add_repair(ssStart, ssbLength, rsId, fecData, performance.now())
3816
+ } catch {
3817
+ // WASM add_repair failure — block will timeout and be marked failed
3818
+ }
3819
+ this.#retireIsoUnplaced(client, packetId, catalogTrackName)
3820
+ if (recovered) this.#syncDecoderBlockOwners.delete(blockKey)
3821
+
3822
+ return recovered
3823
+ }
3824
+
3825
+ #routeSyncCleanup(
3826
+ decoder: WasmFecDecoder,
3827
+ sbn: number,
3828
+ packetId: number,
3829
+ catalogTrackName: string | undefined,
3830
+ ): void {
3831
+ // Retire the block from the decoder. Concealment of a lost block is the
3832
+ // sink's job (hold last good frame), so nothing is routed from here.
3833
+ try {
3834
+ decoder.cleanup_blocks_detailed(Uint32Array.of(sbn))
3835
+ } catch (error) {
3836
+ console.warn(`[FECManager] Scoped cleanup failed for SBN ${sbn}:`, error)
3837
+ }
3838
+ this.#retireIsoUnplaced(decoder, packetId, catalogTrackName)
3839
+ }
3840
+
3841
+ /**
3842
+ * iso-ssbg1-v1: a placed source the decoder took before its block's repair
3843
+ * (fed in wire order, sources first) waits unplaced in the decoder; one
3844
+ * whose repair never reaches it, such as a source of a repair-less span,
3845
+ * would stay there. Retire those by the decoder's horizon behind the newest
3846
+ * SS_ID the stream's locator has seen. Run after every feed that grows the
3847
+ * decoder and when a block is retired, as the fec-worker sweeps its own
3848
+ * pool: a stream that loses only repair symbols never expires a block, so
3849
+ * a sweep tied to expiry alone would never run there.
3850
+ */
3851
+ #retireIsoUnplaced(
3852
+ decoder: WasmFecDecoder,
3853
+ packetId: number,
3854
+ catalogTrackName: string | undefined,
3855
+ ): void {
3856
+ if (!this.#hasBlockProfile(packetId)) return
3857
+ const newest = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newest
3858
+ if (newest === undefined) return
3859
+ try {
3860
+ this.#isoDecoderUnplacedRetired += decoder.retire_unplaced(newest)
3861
+ } catch (error) {
3862
+ this.#isoDecoderUnplacedRetireFailed++
3863
+ const failed = this.#isoDecoderUnplacedRetireFailed
3864
+ if (failed <= 5 || failed % 100 === 0) {
3865
+ console.warn(
3866
+ `[FECManager] iso-ssbg1-v1 unplaced retirement failed for packetId=${packetId} (${failed} total):`,
3867
+ error,
3868
+ )
3869
+ }
3870
+ }
3871
+ }
3872
+
3873
+ // -----------------------------------------------------------------------
3874
+ // Block lifecycle
3875
+ // -----------------------------------------------------------------------
3876
+
3877
+ /**
3878
+ * Track a first-arrival network source symbol for an FEC block. Refreshes
3879
+ * the inactivity deadline on each symbol, records the symbol's in-band
3880
+ * classification evidence, and marks the block clean when all of its
3881
+ * authored source symbols arrived: the SSB_length a repair symbol declared,
3882
+ * otherwise K.
3883
+ *
3884
+ * Throws for a packetId that was never configured, so a classified block
3885
+ * never reads the manager-global K or timeout.
3886
+ */
3887
+ trackBlock(
3888
+ sbn: number,
3889
+ packetId: number,
3890
+ catalogTrackName: string | undefined,
3891
+ esi: number,
3892
+ evidence: SourceSymbolEvidence,
3893
+ ): void {
3894
+ const trackConfig = this.#trackConfigs.get(packetId)
3895
+ if (trackConfig === undefined) {
3896
+ throw new Error(
3897
+ `[FECManager] trackBlock for packetId=${packetId}, which was never configured; ` +
3898
+ 'configure the track from its catalog (configureTrack/setFecWorker/setFecDecoder) first',
3899
+ )
3900
+ }
3901
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
3902
+ const k = trackConfig.k
3903
+
3904
+ // Skip blocks already recovered — late source symbols must not restart timeouts
3905
+ if (this.#completedBlocks.has(key)) return
3906
+
3907
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, 'source', evidence.packetSequenceNumber)
3908
+
3909
+ // A source ESI at or past the block's authored SSB_length contradicts it;
3910
+ // its geometry can no longer be trusted, so fail it closed.
3911
+ const authoredLength = this.#blockAuthoredLengths.get(key) ?? k
3912
+ if (Number.isInteger(esi) && esi! >= authoredLength) {
3913
+ this.#failBlock(sbn, packetId, catalogTrackName)
3914
+ return
3915
+ }
3916
+
3917
+ this.#applyClassifierChanges(
3918
+ packetId,
3919
+ catalogTrackName,
3920
+ this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence),
3921
+ )
3922
+
3923
+ // Count source symbols per block
3924
+ const count = (this.#blockSourceCounts.get(key) ?? 0) + 1
3925
+ this.#blockSourceCounts.set(key, count)
3926
+ if (count === 1) this.#indexBlockKey(key, sbn, packetId)
3927
+ if (Number.isInteger(esi) && esi! >= 0 && esi! < k) {
3928
+ let sourceEsis = this.#blockSourceEsis.get(key)
3929
+ if (!sourceEsis) {
3930
+ sourceEsis = new Set()
3931
+ this.#blockSourceEsis.set(key, sourceEsis)
3932
+ }
3933
+ sourceEsis.add(esi!)
3934
+ }
3935
+ if (count === 1) {
3936
+ if (catalogTrackName === undefined) {
3937
+ this.onBlockStarted?.(sbn, packetId)
3938
+ } else {
3939
+ this.onBlockStarted?.(sbn, packetId, catalogTrackName)
3940
+ }
3941
+ }
3942
+
3943
+ // When every authored source symbol arrived (SSB_length once a repair
3944
+ // symbol declared it, otherwise K), the block is clean: no loss, no FEC.
3945
+ if (k > 0 && count >= authoredLength) {
3946
+ this.#completeCleanBlock(key, sbn, packetId, catalogTrackName)
3947
+ return
3948
+ }
3949
+
3950
+ this.noteBlockActivity(sbn, packetId, catalogTrackName, true)
3951
+
3952
+ // Source ESI is intentionally not a repair trigger. Multicast delivery is
3953
+ // unordered, so K-1 may precede an interior symbol in a clean block. The
3954
+ // progress-refreshed source horizon above is the earliest loss signal.
3955
+ }
3956
+
3957
+ #completeCleanBlock(
3958
+ key: string,
3959
+ sbn: number,
3960
+ packetId: number,
3961
+ catalogTrackName?: string,
3962
+ ): void {
3963
+ this.#fecStats.blocksClean++
3964
+ this.#statsForPacket(packetId).blocksClean++
3965
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName)
3966
+ this.#blockSourceCounts.delete(key)
3967
+ this.#blockSourceEsis.delete(key)
3968
+ this.#blockAuthoredLengths.delete(key)
3969
+ this.#blockRepairRsIds.delete(key)
3970
+ // BLO-3323 L15: track which SBNs reached K source-symbol arrivals so the
3971
+ // worker recovery suppression can distinguish "block completed by source"
3972
+ // (legitimately suppress duplicate recovery) from "block touched by any
3973
+ // prior emit / timeout / external mark" (do NOT suppress recovery).
3974
+ // #markTerminal retires both memberships together (BLO-36599).
3975
+ this.#markTerminal(key, sbn, packetId, true)
3976
+ this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
3977
+ if (catalogTrackName === undefined) {
3978
+ this.onBlockComplete?.(sbn, packetId)
3979
+ } else {
3980
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName)
3981
+ }
3982
+ // MmtpRouter feeds the K-th source immediately after this callback.
3983
+ // Defer cleanup so that synchronous feed selects the same decoder; this
3984
+ // also clears blocks whose K-th packet was too large for decoder input.
3985
+ queueMicrotask(() => this.#syncDecoderBlockOwners.delete(key))
3986
+ }
3987
+
3988
+ /** Refresh deadlines after accepted block activity. */
3989
+ noteBlockActivity(
3990
+ sbn: number,
3991
+ packetId: number,
3992
+ catalogTrackName?: string,
3993
+ sourceProgress = false,
3994
+ ): void {
3995
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
3996
+
3997
+ // Late symbols must not resurrect a block that already completed or failed.
3998
+ if (this.#completedBlocks.has(key)) return
3999
+ // The worker cleanup command is already queued after all symbols that made
4000
+ // the inactivity deadline. Symbols arriving after that boundary are late
4001
+ // and must not arm a second timer before the acknowledgement resolves it.
4002
+ if (this.#pendingWorkerCleanups.has(key)) return
4003
+
4004
+ const repairRequested = this.#repairRequestedBlocks.has(key)
4005
+ // An ordered relay already decided a requested block by stream order; its
4006
+ // fate is the scheduler's hold (or its absence), never a re-hold.
4007
+ if (repairRequested && this.#settlesByOrder(key)) return
4008
+
4009
+ // An ordered relay's pauses say nothing about loss; stream order settles
4010
+ // the block (see MulticastSymbolDelivery). No timer is armed for it.
4011
+ if (this.#settlesByOrder(key)) {
4012
+ this.#holdForOrderedSettlement(key, sbn, packetId, catalogTrackName)
4013
+ return
4014
+ }
4015
+
4016
+ const trackConfig = this.#resolveTrackConfig(packetId)
4017
+ const timeoutMs = this.#multicastWaitMs(trackConfig)
4018
+ // #computeTimeout never yields <= 0 (computeFecDeliveryWindowMs throws on
4019
+ // a non-positive interleave or K). Returning here would leave a block
4020
+ // with source counted but no fail deadline, 'pending' forever, so a
4021
+ // violated invariant must fail loudly instead.
4022
+ if (!(timeoutMs > 0)) {
4023
+ throw new Error(`[FECManager] packetId=${packetId} has no positive fail bound (timeoutMs=${timeoutMs})`)
4024
+ }
4025
+
4026
+ // D-28: accepted source progress refreshes the pre-request horizon. There
4027
+ // are at most K such arrivals; repair traffic never refreshes this timer.
4028
+ // A requested block's accepted symbols keep extending its multicast wait
4029
+ // (a late symbol can still complete it) but never re-arm the request: at
4030
+ // most K+P accepted symbols can move the wait, so the block stays bounded.
4031
+ const repairDeadline = this.#repairDeadlines.get(key)
4032
+ if (
4033
+ this.onRepairNeeded &&
4034
+ !repairRequested &&
4035
+ (repairDeadline === undefined || sourceProgress)
4036
+ ) {
4037
+ this.#armRepairDeadline(
4038
+ key,
4039
+ sbn,
4040
+ packetId,
4041
+ catalogTrackName,
4042
+ this.#repairDeadlineMs(trackConfig),
4043
+ )
4044
+ }
4045
+
4046
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs)
4047
+ }
4048
+
4049
+ #failBlock(
4050
+ sbn: number,
4051
+ packetId: number,
4052
+ catalogTrackName?: string,
4053
+ ): void {
4054
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
4055
+ this.#traceLifecycle('failed', sbn, packetId, catalogTrackName)
4056
+ this.#clearRepairDeadline(key)
4057
+ this.#clearBlockTimer(key)
4058
+ const blockClass = this.#retireBlockClass(key, sbn, packetId, catalogTrackName)
4059
+ if (this.#repairRequestedBlocks.delete(key)) {
4060
+ this.onRepairResolved?.(sbn, packetId, 'failed', catalogTrackName, null)
4061
+ }
4062
+ this.#blockSourceCounts.delete(key)
4063
+ this.#blockSourceEsis.delete(key)
4064
+ this.#blockAuthoredLengths.delete(key)
4065
+ this.#blockRepairRsIds.delete(key)
4066
+ this.#syncDecoderBlockOwners.delete(key)
4067
+ this.#markTerminal(key, sbn, packetId, false)
4068
+ this.#failedBlocks.add(key)
4069
+ this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
4070
+ this.#fecStats.blocksFailed++
4071
+ this.#statsForPacket(packetId).blocksFailed++
4072
+ this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass)
4073
+ this.onBlockResolved?.(sbn, packetId, catalogTrackName)
4074
+ }
4075
+
4076
+ /**
4077
+ * Resolve a block as completed (clean, recovered, or externally marked).
4078
+ * A block that had a D-28 repair outstanding counts as repaired: it was
4079
+ * short of its source at the repair deadline and completed anyway.
4080
+ */
4081
+ #resolveCompleted(key: string): void {
4082
+ const block = this.#parseBlockKey(key)
4083
+ this.#markTerminal(key, block.sbn, block.packetId, false)
4084
+ this.#clearOwedCleanupBound(key)
4085
+ this.#pendingWorkerCleanups.delete(key)
4086
+ this.#pendingWorkerCleanupClients.delete(key)
4087
+ this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName)
4088
+ this.#clearRepairDeadline(key)
4089
+ if (this.#repairRequestedBlocks.delete(key)) {
4090
+ this.#noteBlockRepaired(key, block.sbn, block.packetId, block.catalogTrackName)
4091
+ this.onRepairResolved?.(
4092
+ block.sbn,
4093
+ block.packetId,
4094
+ 'completed',
4095
+ block.catalogTrackName,
4096
+ this.#viaFor(key),
4097
+ )
4098
+ }
4099
+ this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName)
4100
+ this.#blockSourceCounts.delete(key)
4101
+ this.#blockSourceEsis.delete(key)
4102
+ this.#blockAuthoredLengths.delete(key)
4103
+ this.#blockRepairRsIds.delete(key)
4104
+ this.#clearBlockTimer(key)
4105
+ this.onBlockResolved?.(block.sbn, block.packetId, block.catalogTrackName)
4106
+ }
4107
+
4108
+ /** Check whether a block has already been completed (clean or recovered). */
4109
+ isBlockCompleted(sbn: number, packetId?: number, catalogTrackName?: string): boolean {
4110
+ return this.#blockKeysFor(sbn, packetId, catalogTrackName).some((key) => this.#completedBlocks.has(key))
4111
+ }
4112
+
4113
+ /** Mark a block as completed externally (e.g., after routing recovered data). */
4114
+ markBlockCompleted(sbn: number, packetId?: number, catalogTrackName?: string): void {
4115
+ for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
4116
+ this.#resolveCompleted(key)
4117
+ }
4118
+ }
4119
+
4120
+ /**
4121
+ * Increment blocksRecovered (called by MmtpRouter after routing a
4122
+ * synchronous recovery). With the block's coordinates the recovery is also
4123
+ * reported through onBlockRepaired, once per block.
4124
+ */
4125
+ countRecovery(packetId?: number, sbn?: number, catalogTrackName?: string): void {
4126
+ this.#fecStats.blocksRecovered++
4127
+ if (packetId != null) this.#statsForPacket(packetId).blocksRecovered++
4128
+ if (packetId != null && sbn != null) {
4129
+ this.#noteBlockRepaired(
4130
+ this.#blockKey(sbn, packetId, catalogTrackName),
4131
+ sbn,
4132
+ packetId,
4133
+ catalogTrackName,
4134
+ )
4135
+ }
4136
+ }
4137
+
4138
+ /**
4139
+ * Strict delivery provenance for one FEC block.
4140
+ *
4141
+ * A recovered symbol is a function of every symbol that entered its block,
4142
+ * so it can only be attributed to multicast when NO symbol in that block
4143
+ * arrived over MoQ. Repair symbols routinely arrive over reliable QUIC
4144
+ * (`MmtpRouter.feedRepairPacket`), so a block that recovered with MoQ help
4145
+ * produced bytes that never crossed a multicast socket.
4146
+ *
4147
+ * An untracked block returns 'unknown' rather than a guess: absence of
4148
+ * evidence is not evidence of multicast.
4149
+ */
4150
+ blockDeliveryProvenance(
4151
+ sbn: number,
4152
+ packetId: number,
4153
+ catalogTrackName?: string,
4154
+ ): MmtpDeliveryProvenance {
4155
+ const counts = this.blockPathCount(sbn, packetId, catalogTrackName)
4156
+ if (!counts) return 'unknown'
4157
+ if (counts.moqSymbols > 0) return 'mixed'
4158
+ if (counts.multicastSymbols > 0) return 'multicast'
4159
+ return 'unknown'
4160
+ }
4161
+
4162
+ /** Per-path symbol counts for one block (D-28 gate logging), if tracked. */
4163
+ blockPathCount(
4164
+ sbn: number,
4165
+ packetId: number,
4166
+ catalogTrackName?: string,
4167
+ ): FecBlockPathCount | null {
4168
+ return this.#blockPathCounts.get(
4169
+ this.#blockKey(sbn, packetId, catalogTrackName),
4170
+ ) ?? null
4171
+ }
4172
+
4173
+ /** Cancel block timeout (block completed via clean reception or FEC recovery). */
4174
+ cancelBlockTimeout(sbn: number, packetId?: number, catalogTrackName?: string): void {
4175
+ for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
4176
+ this.#resolveCompleted(key)
4177
+ }
4178
+ }
4179
+
4180
+ // -----------------------------------------------------------------------
4181
+ // Cleanup
4182
+ // -----------------------------------------------------------------------
4183
+
4184
+ dispose(): void {
4185
+ for (const timer of this.#activeBlocks.values()) {
4186
+ if (timer.handle != null) clearTimeout(timer.handle)
4187
+ }
4188
+ this.#activeBlocks.clear()
4189
+ this.#activeBlockDeadlinesMs.clear()
4190
+ this.#blockWaitDeadlinesMs.clear()
4191
+ this.#repairHoldUntilMs.clear()
4192
+ this.#deliveryGaps.reset()
4193
+ this.#pendingWorkerCleanups.clear()
4194
+ this.#pendingWorkerCleanupClients.clear()
4195
+ for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle)
4196
+ this.#pendingWorkerCleanupBounds.clear()
4197
+ for (const timer of this.#repairDeadlines.values()) {
4198
+ if (timer?.handle != null) clearTimeout(timer.handle)
4199
+ }
4200
+ this.#repairDeadlines.clear()
4201
+ this.#repairDeadlineAtMs.clear()
4202
+ this.#terminalExpiryMs.clear()
4203
+ this.#terminalQueues.clear()
4204
+ this.#blockKeysBySbn.clear()
4205
+ this.#blockSourceCounts.clear()
4206
+ this.#blockSourceEsis.clear()
4207
+ this.#blockAuthoredLengths.clear()
4208
+ this.#blockRepairRsIds.clear()
4209
+ this.#completedBlocks.clear()
4210
+ this.#cleanlyCompletedBlocks.clear()
4211
+ this.#repairRequestedBlocks.clear()
4212
+ this.#workerRecoveredBlocks.clear()
4213
+ this.#syncDecoderBlockOwners.clear()
4214
+ this.#startupAlignedPackets.clear()
4215
+ this.#startupPartialBlocks.clear()
4216
+ this.#startupRequireRepairReady = false
4217
+ this.#startupRepairReadyPackets.clear()
4218
+ this.#startupRepairBoundaryCounts.clear()
4219
+ this.#startupRepairFailOpenPackets.clear()
4220
+ this.#orderedFrontiers.clear()
4221
+ this.#orderedPendingBlocks.clear()
4222
+ this.#seenSymbols.clear()
4223
+ this.#blockPathCounts.clear()
4224
+ this.#blockAnchorsMs.clear()
4225
+ this.#blockCatalogTrackNames.clear()
4226
+ this.#classifiers.clear()
4227
+ this.#streamGeometries.clear()
4228
+ this.#failedBlocks.clear()
4229
+ this.#resolvedBlockClasses.clear()
4230
+ this.#repairedBlocks.clear()
4231
+ this.#materializedBlocks.clear()
4232
+ this.#highestSbn.clear()
4233
+ this.#isoLocators.clear()
4234
+ this.#sourceAnchors.clear()
4235
+ this.#trackConfigs.clear()
4236
+ this.#fecDecoders.clear()
4237
+ // Dispose Worker clients (T-03-07: prevent Worker leak)
4238
+ for (const client of new Set(this.#workerClients.values())) client.dispose()
4239
+ this.#workerClients.clear()
4240
+ }
4241
+ }