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