@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,2895 @@
1
+ /**
2
+ * Facade composing FECManager + MmtpRouter + MulticastTransport.
3
+ *
4
+ * Public methods delegate to the decomposed components. Applications that
5
+ * need individual layers can use them directly:
6
+ * - FECManager — codec-agnostic FEC decode
7
+ * - MmtpRouter — MMTP packet parsing + frame routing
8
+ * - MulticastTransport — SSM join/socket/watchdog
9
+ */
10
+
11
+ import { parseFecBlockProfile, type FecBlockProfile } from "@blockcast/mmt-base";
12
+ import {
13
+ FECManager,
14
+ MIN_INTERLEAVE_DEPTH_MS,
15
+ type FECManagerConfig,
16
+ type WasmFecDecoder,
17
+ type FecDecoderUnavailableReason,
18
+ type FecFallbackDecoder,
19
+ type MulticastSymbolDelivery,
20
+ type RepairVia,
21
+ } from "./fec-manager.js";
22
+ import {
23
+ deriveBlockClassifierGeometry,
24
+ repairPriorityForClass,
25
+ type BlockClass,
26
+ type ClassifierMode,
27
+ type ClassifierReason,
28
+ type FrameGapDecision,
29
+ type ReclassificationEvidence,
30
+ type RepairPriority,
31
+ type TrackKind,
32
+ } from "./block-policy.js";
33
+ import type {
34
+ RepairFetchHost,
35
+ RepairPriorityReason,
36
+ RepairSkipReason,
37
+ RepairSubscribeCallback,
38
+ } from "./repair-fetch.js";
39
+ import {
40
+ MmtpRouter,
41
+ type FrameCallback,
42
+ type ManifestIdentityResolver,
43
+ type MmtpIngressContext,
44
+ type MmtpStreamIdentity,
45
+ type StagedStreamSwitch,
46
+ type StreamSwitchCommit,
47
+ type TrackPacketCallback,
48
+ } from "./mmtp-router.js";
49
+ import { isMulticastTrackPacketId } from "@blockcast/mmt-transport";
50
+ import {
51
+ MulticastTransport,
52
+ type MulticastFailbackReason,
53
+ type MulticastJoinOutcome,
54
+ type MulticastJoinStats,
55
+ } from "./multicast-transport.js";
56
+ import { computeFecDeliveryWindowMs } from "./track-session.js";
57
+ import { DEFAULT_AMT_RELAY_PORT } from "./catalog-network-source.js";
58
+ import { deriveFecInterleaveDepth, FecBlockMapper } from "@blockcast/mmt-fec";
59
+ import type {
60
+ FecBlockSnapshot,
61
+ FecTrackConfig,
62
+ FecTrackStats,
63
+ FecWorkerClient,
64
+ } from "@blockcast/fec-worker";
65
+ import type { MfuReassemblerBackend } from "./mfu-reassembler.js";
66
+ import type { MfuReassemblyPolicy } from "./mfu-reassembly-policy.js";
67
+ import type {
68
+ ManifestObjectIdentity,
69
+ ManifestVerifier,
70
+ } from "@blockcast/mmt-manifest-verify";
71
+ import type {
72
+ BlockAssemblerConfig,
73
+ CmafBlockSample,
74
+ } from "./cmaf-block-assembler.js";
75
+ import {
76
+ hasSwitchingSetRole,
77
+ parseTrackRole,
78
+ validateSwitchingSet,
79
+ isFecCatalogConfig,
80
+ isFecCatalogGeometry,
81
+ type FecCatalogConfig,
82
+ type TrackRole,
83
+ } from "./carp-catalog.js";
84
+ import { catalogFecUnavailable, type TrackFecUnavailable } from "./catalog-fec-params.js";
85
+
86
+ export interface MulticastEndpointConfig {
87
+ sourceAddress: string;
88
+ groupAddress: string;
89
+ port: number;
90
+ /** Explicit gateway transport policy. Omitted means gateway-selected auto mode. */
91
+ mode?: 'auto' | 'native' | 'tunnel';
92
+ /** AMT relay hostname/IP from catalog endpoint. */
93
+ relayAddress?: string;
94
+ /** AMT relay port from catalog endpoint. */
95
+ relayPort?: number;
96
+ /** AMT relay hostname/IP from player/UI overrides. Wins over `relayAddress`. */
97
+ amtRelay?: string;
98
+ /** AMT relay port from player/UI overrides. Wins over `relayPort`. */
99
+ amtRelayPort?: number;
100
+ /** MMTP packet IDs to forward before data enters the page transport queue. */
101
+ packetIds?: number[];
102
+ /** Exact catalog tracks carried by this physical multicast endpoint. */
103
+ tracks?: MmtpIngressContext["tracks"];
104
+ /**
105
+ * The catalog `fec.blockProfile` (BLO-35597): `iso-ssbg1-v1`, the only
106
+ * profile (the retired `k-padded-v1` token is refused). Required for
107
+ * per-track FEC configuration; never defaulted.
108
+ */
109
+ fecBlockProfile?: FecBlockProfile;
110
+ fecK?: number;
111
+ /** Number of repair symbols per FEC block (P). Used to size recovery reorder latency. */
112
+ fecRepairSymbols?: number;
113
+ /** Symbol size in bytes (T). NOT repair count. */
114
+ fecSymbolSize?: number;
115
+ /** Catalog fec.reorderToleranceMs — signaled jitter/reorder allowance, ADDED
116
+ * to the derived delivery window. Never a multiplier on the span, so one
117
+ * network yields the same slack on a wide video span and a narrow audio one.
118
+ *
119
+ * Absence widens the window by zero rather than throwing, unlike the datagram
120
+ * MFU deadline in hang-mmt-fec. The distinction is which way absence fails:
121
+ * there the tolerance IS the deadline's slack term and guessing one invents
122
+ * a reorder budget, so it must fail loud; here the window is already fully
123
+ * derived from other catalog values and the tolerance only widens it, so
124
+ * adding nothing is the identity and errs toward earlier failback. Do not
125
+ * "harmonize" this into a throw, and do not turn the zero into a default. */
126
+ fecReorderToleranceMs?: number;
127
+ fecInterleaveDepthMs?: number;
128
+ /** Aggregate endpoint bandwidth in bits per second from the multicast catalog. */
129
+ bandwidth?: number;
130
+ fps?: number;
131
+ /** Track media kind (repair class `audio` vs video block classification). */
132
+ trackKind?: TrackKind;
133
+ /** Catalog codec string (video conceal mode, codec-aware RAP checks). */
134
+ codec?: string;
135
+ /** Catalog track timescale for `keyframeIntervalTicks`. */
136
+ timescale?: number;
137
+ /** Raw catalog `keyframeIntervalTicks` (never a resolved cadence). */
138
+ keyframeIntervalTicks?: number;
139
+ /** Raw catalog `keyframeIntervalMs` (never a resolved cadence). */
140
+ keyframeIntervalMs?: number;
141
+ /** Catalog-derived lower bound for packet-silence failback (for example, keyframe repair cadence). */
142
+ minimumFailbackWindowMs?: number;
143
+ }
144
+ export interface MulticastManagerOptions {
145
+ /**
146
+ * MFU reassembly timeout (ms). Threaded to the inner MmtpRouter (and its
147
+ * MmtpContainerParser). Caller derives from catalog `fec.interleaveDepthMs`,
148
+ * which is already in milliseconds — `moqenc_mmt.c` converts
149
+ * `depth_ms = fec_depth * (1000/fps)` before populating the catalog.
150
+ * Defaults to 1000ms (with parser warning) when omitted.
151
+ */
152
+ mfuTimeoutMs?: number;
153
+ reassemblyPolicy?: MfuReassemblyPolicy;
154
+ reassembler?: MfuReassemblerBackend;
155
+ maxBufferedMfus?: number;
156
+ manifestVerifier?: ManifestVerifier;
157
+ manifestVerifierOwnership?: "caller" | "router";
158
+ resolveManifestIdentity?: (
159
+ packetId: number,
160
+ sbn: number,
161
+ esi: number,
162
+ catalogTrackName?: string,
163
+ ) => ManifestObjectIdentity | null;
164
+ resolveManifestIdentityForRoute?: ManifestIdentityResolver;
165
+ /**
166
+ * Also write every repair lifecycle event to the console as one
167
+ * `REPAIR_LIFECYCLE_LOG_PREFIX` JSON line. Off unless asked for: the lines
168
+ * are serialized on the page thread for every failed block and repair step
169
+ * (and again for an attached inspector), and addRepairLifecycleObserver is
170
+ * the lifecycle API. Enable only for interactive debugging (BLO-36599).
171
+ */
172
+ logRepairLifecycle?: boolean;
173
+ }
174
+
175
+ /**
176
+ * An in-place video rendition switch on the live join: MulticastManager
177
+ * .switchRendition. Every rendition of a ladder can share one SSM group and
178
+ * differ only by MMTP packet ID, so the switch remaps packet IDs at a RAP
179
+ * instead of leaving and re-joining the group.
180
+ */
181
+ export interface RenditionSwitchRequest {
182
+ /** The rendition playing now: an ingress track of the live join. */
183
+ readonly from: MmtpStreamIdentity;
184
+ /**
185
+ * The rendition replacing it, already registered as video with everything
186
+ * it plays through (setPacketIdType, setTrackCodec, configureTrackFec, its
187
+ * FEC decoder, frame and init callbacks, MSE assembler, repair owner).
188
+ */
189
+ readonly to: MmtpStreamIdentity;
190
+ /**
191
+ * The live join's complete ingress once the switch commits: every track
192
+ * that stays admitted (audio, repair legs) plus `to` and its repair legs.
193
+ * It must carry `to`, nothing on `from`'s packet ID (the commit retires
194
+ * it), and no live packet ID under another name.
195
+ */
196
+ readonly tracks: MmtpIngressContext["tracks"];
197
+ /**
198
+ * The allow-list once the switch commits, when it changes: an allow-list
199
+ * scoped to the active rendition. Omit it for a rendition-stable allow-list
200
+ * that already admits `to`; the live allow-list is then kept unchanged.
201
+ */
202
+ readonly packetIds?: readonly number[];
203
+ /**
204
+ * Called synchronously at the commit, inside the frame path, after `from`
205
+ * is retired and the admission narrowed, and before `to`'s newest init and
206
+ * its RAP are delivered: reconfigure the decoder here. Throwing fails the
207
+ * switch (`commit-failed`): `from` cannot be restored, so `to` is retired
208
+ * as well and none of it is delivered.
209
+ */
210
+ readonly onCommit: (commit: StreamSwitchCommit) => void;
211
+ /** Called once when the switch ends without a completed commit. */
212
+ readonly onCancel: (cancel: RenditionSwitchCancel) => void;
213
+ }
214
+
215
+ /**
216
+ * Why a staged rendition switch ended without a completed commit.
217
+ *
218
+ * - `cancelled`: RenditionSwitch.cancel().
219
+ * - `superseded`: join() or dispose() replaced the admission it was staged on.
220
+ * - `provider-refused`: the subscription refused to widen its packet filter to
221
+ * `to`, so `to` can never arrive.
222
+ * - `commit-failed`: `onCommit` threw. `from` was already retired, so `to` is
223
+ * retired as well and the subscription now delivers neither rendition;
224
+ * recover with join().
225
+ */
226
+ export type RenditionSwitchCancel =
227
+ | { readonly reason: "cancelled" }
228
+ | { readonly reason: "superseded" }
229
+ | { readonly reason: "provider-refused"; readonly error: unknown }
230
+ | { readonly reason: "commit-failed"; readonly error: unknown };
231
+
232
+ export type RenditionSwitchState = "staged" | "committed" | "cancelled" | "failed";
233
+
234
+ /** A rendition switch MulticastManager.switchRendition staged. */
235
+ export interface RenditionSwitch {
236
+ readonly state: RenditionSwitchState;
237
+ /**
238
+ * Abandon the switch before it commits: the pre-switch admission is
239
+ * restored and `to` is retired (its router registrations and FEC state
240
+ * released). Returns false once the switch committed or ended.
241
+ */
242
+ cancel(): boolean;
243
+ }
244
+
245
+ interface ActiveRenditionSwitch {
246
+ readonly from: MmtpStreamIdentity;
247
+ readonly to: MmtpStreamIdentity;
248
+ readonly onCommit: (commit: StreamSwitchCommit) => void;
249
+ readonly onCancel: (cancel: RenditionSwitchCancel) => void;
250
+ /** The admission the switch was staged on, restored by cancel(). */
251
+ readonly liveIngress: MmtpIngressContext;
252
+ readonly livePacketIds: ReadonlySet<number> | null;
253
+ /** True when staging widened the allow-list (so cancel narrows it back). */
254
+ readonly widened: boolean;
255
+ /** The admission once committed. */
256
+ readonly committedIngress: MmtpIngressContext;
257
+ readonly committedPacketIds: readonly number[] | undefined;
258
+ router: StagedStreamSwitch | null;
259
+ state: RenditionSwitchState;
260
+ }
261
+
262
+ function freezeIngress(tracks: Iterable<Readonly<{ name: string; packetId: number }>>): MmtpIngressContext {
263
+ return Object.freeze({
264
+ tracks: Object.freeze(
265
+ [...tracks].map(({ name, packetId }) => Object.freeze({ name, packetId })),
266
+ ),
267
+ });
268
+ }
269
+
270
+ function sameIdSet(a: ReadonlySet<number>, b: ReadonlySet<number>): boolean {
271
+ if (a.size !== b.size) return false;
272
+ for (const id of a) if (!b.has(id)) return false;
273
+ return true;
274
+ }
275
+
276
+ export interface RepairStreamIdentity {
277
+ readonly packetId: number;
278
+ /** Non-empty catalog identity, or null when the producer has no track name. */
279
+ readonly catalogTrackName: string | null;
280
+ }
281
+
282
+ export interface RepairBlockIdentity extends RepairStreamIdentity {
283
+ readonly sbn: number;
284
+ }
285
+
286
+ interface RepairSymbolCounts {
287
+ readonly multicast: number;
288
+ readonly moq: number;
289
+ }
290
+
291
+ /**
292
+ * Typed repair lifecycle, version 2 (keyframe-protected FEC policy). One
293
+ * clean cut from version 1: there is no v1 emit and no alias.
294
+ *
295
+ * - `requested`: a block short of its source at the repair deadline; its
296
+ * class sets the QUIC repair priority (P0 keyframe/unknown, P1 audio,
297
+ * P2 delta).
298
+ * - `reclassified`: new evidence (or a disabled classifier) changed a block's
299
+ * class.
300
+ * - `recovered` / `failed`: every block that could not complete from its
301
+ * first-arrival source symbols resolves with exactly one of these.
302
+ * - `repair-preempted` / `repair-deferred`: the scheduler aborted a delta
303
+ * repair for keyframe work, or never ran it before its block resolved.
304
+ * - `repair-priority`: the catalog could not supply the SUBSCRIBER_PRIORITY a
305
+ * repair FETCH must carry (draft-ramadan-moq-fec §11.4.5), so the FETCH was
306
+ * sent without the parameter (`omitted`, keyframe/unknown blocks) or not
307
+ * sent at all (`declined`, delta/audio blocks).
308
+ * - `classifier`: a video stream's classifier mode and why.
309
+ * - `gap`: the stall/conceal decision attached to the first frame released
310
+ * after a lossy gap — the very object carried as `gapBefore`.
311
+ * - `decoder-unavailable`: a stream's Worker decoder left routing.
312
+ */
313
+ export type RepairLifecycleEvent =
314
+ | {
315
+ readonly version: 2;
316
+ readonly type: "requested";
317
+ readonly block: RepairBlockIdentity;
318
+ readonly blockClass: BlockClass;
319
+ readonly priority: RepairPriority;
320
+ }
321
+ | {
322
+ readonly version: 2;
323
+ readonly type: "reclassified";
324
+ readonly block: RepairBlockIdentity;
325
+ readonly from: BlockClass;
326
+ readonly to: BlockClass;
327
+ readonly evidence: ReclassificationEvidence;
328
+ }
329
+ | {
330
+ readonly version: 2;
331
+ readonly type: "recovered";
332
+ readonly block: RepairBlockIdentity;
333
+ readonly blockClass: BlockClass;
334
+ readonly via: RepairVia;
335
+ readonly symbols: RepairSymbolCounts;
336
+ }
337
+ | {
338
+ readonly version: 2;
339
+ readonly type: "failed";
340
+ readonly block: RepairBlockIdentity;
341
+ readonly blockClass: BlockClass;
342
+ readonly symbols: RepairSymbolCounts;
343
+ }
344
+ | {
345
+ readonly version: 2;
346
+ readonly type: "repair-preempted" | "repair-deferred";
347
+ readonly block: RepairBlockIdentity;
348
+ }
349
+ | {
350
+ readonly version: 2;
351
+ /**
352
+ * The scheduler sent no FETCH for a requested block (BLO-35597): the
353
+ * measured reliable-path RTT could not come back before the block's
354
+ * presentation deadline, the path offered no RTT, or the player gave
355
+ * no presentation delay. `rttMs` is null when unmeasured; `budgetMs` is
356
+ * the time that was left to the deadline.
357
+ */
358
+ readonly type: "repair-skipped";
359
+ readonly block: RepairBlockIdentity;
360
+ readonly reason: RepairSkipReason;
361
+ readonly rttMs: number | null;
362
+ readonly budgetMs: number;
363
+ }
364
+ | {
365
+ readonly version: 2;
366
+ readonly type: "repair-priority";
367
+ readonly block: RepairBlockIdentity;
368
+ readonly blockClass: BlockClass;
369
+ readonly action: "omitted" | "declined";
370
+ readonly reason: RepairPriorityReason;
371
+ }
372
+ | {
373
+ readonly version: 2;
374
+ readonly type: "classifier";
375
+ readonly stream: RepairStreamIdentity;
376
+ readonly mode: ClassifierMode;
377
+ readonly reason: ClassifierReason | null;
378
+ }
379
+ | FrameGapDecision
380
+ | {
381
+ readonly version: 2;
382
+ /**
383
+ * The stream's Worker decoder left routing (FECManager.clearFecWorker,
384
+ * or a disposed client evicted on its next symbol). `fallbackDecoder`
385
+ * says what still decodes the stream: 'sync' when a synchronous WASM
386
+ * decoder registered for the same stream keeps serving it, 'none' when
387
+ * nothing does. Only 'none' means the stream's symbols reach no decoder
388
+ * until a host registers one again; consumers fail closed on that
389
+ * instead of reading the following silence as a clean stream.
390
+ */
391
+ readonly type: "decoder-unavailable";
392
+ readonly stream: RepairStreamIdentity;
393
+ readonly reason: FecDecoderUnavailableReason;
394
+ readonly fallbackDecoder: FecFallbackDecoder;
395
+ };
396
+
397
+ /**
398
+ * Keyframe-protected repair policy counters for one catalog track. Reset
399
+ * whenever the track's epoch changes (catalog geometry change or reset).
400
+ *
401
+ * "Protected" means the block was short of its source at the repair deadline
402
+ * with class `keyframe` or `unknown`. The `keyframe*` recovered/failed
403
+ * counters cover every P0 block (class `keyframe` or `unknown`).
404
+ */
405
+ export interface BlockPolicyStats {
406
+ readonly packetId: number;
407
+ readonly catalogTrackName: string | null;
408
+ readonly epoch: number;
409
+ classifierMode: ClassifierMode | null;
410
+ classifierReason: ClassifierReason | null;
411
+ keyframeBlocksProtected: number;
412
+ unknownBlocksProtected: number;
413
+ keyframeBlocksRecoveredInband: number;
414
+ keyframeBlocksRecoveredQuic: number;
415
+ keyframeBlocksFailed: number;
416
+ deltaBlocksShort: number;
417
+ deltaBlocksRecoveredInband: number;
418
+ deltaBlocksRecoveredQuic: number;
419
+ deltaRepairsPreempted: number;
420
+ deltaRepairsDeferred: number;
421
+ /** Repair requests sent no FETCH (see the `repair-skipped` event). */
422
+ repairsSkipped: number;
423
+ deltaBlocksFailed: number;
424
+ audioBlocksRecoveredInband: number;
425
+ audioBlocksRecoveredQuic: number;
426
+ audioBlocksFailed: number;
427
+ stalls: number;
428
+ concealedBlocks: number;
429
+ concealedGaps: number;
430
+ concealedFrames: number;
431
+ concealedAudioMs: number;
432
+ vanishedBlocks: number;
433
+ }
434
+
435
+ function newBlockPolicyStats(
436
+ packetId: number,
437
+ catalogTrackName: string | null,
438
+ epoch: number,
439
+ ): BlockPolicyStats {
440
+ return {
441
+ packetId,
442
+ catalogTrackName,
443
+ epoch,
444
+ classifierMode: null,
445
+ classifierReason: null,
446
+ keyframeBlocksProtected: 0,
447
+ unknownBlocksProtected: 0,
448
+ keyframeBlocksRecoveredInband: 0,
449
+ keyframeBlocksRecoveredQuic: 0,
450
+ keyframeBlocksFailed: 0,
451
+ deltaBlocksShort: 0,
452
+ deltaBlocksRecoveredInband: 0,
453
+ deltaBlocksRecoveredQuic: 0,
454
+ deltaRepairsPreempted: 0,
455
+ deltaRepairsDeferred: 0,
456
+ repairsSkipped: 0,
457
+ deltaBlocksFailed: 0,
458
+ audioBlocksRecoveredInband: 0,
459
+ audioBlocksRecoveredQuic: 0,
460
+ audioBlocksFailed: 0,
461
+ stalls: 0,
462
+ concealedBlocks: 0,
463
+ concealedGaps: 0,
464
+ concealedFrames: 0,
465
+ concealedAudioMs: 0,
466
+ vanishedBlocks: 0,
467
+ };
468
+ }
469
+
470
+ export type RepairLifecycleObserver = (event: RepairLifecycleEvent) => void;
471
+
472
+ export interface RepairLifecycleSource {
473
+ addRepairLifecycleObserver(observer: RepairLifecycleObserver): () => void;
474
+ }
475
+
476
+ /** Minimal event shape accepted by application-owned event targets. */
477
+ export interface RepairLifecycleApplicationEvent {
478
+ readonly type: string;
479
+ readonly detail: RepairLifecycleEvent;
480
+ }
481
+
482
+ /** DOM EventTarget event shape, including the Node 18 Event fallback. */
483
+ export interface RepairLifecycleDomEvent extends Event {
484
+ readonly detail: RepairLifecycleEvent;
485
+ }
486
+
487
+ /** Structural target contract shared by DOM and Closure-style event targets. */
488
+ export interface RepairLifecycleEventTarget<
489
+ TEvent extends RepairLifecycleApplicationEvent,
490
+ > {
491
+ dispatchEvent(event: TEvent): unknown;
492
+ }
493
+
494
+ export interface RepairLifecycleEventOptions<
495
+ TEvent extends RepairLifecycleApplicationEvent = RepairLifecycleDomEvent,
496
+ > {
497
+ bubbles?: boolean;
498
+ composed?: boolean;
499
+ createEvent?: RepairLifecycleEventFactory<TEvent>;
500
+ }
501
+
502
+ export type RepairLifecycleEventFactory<
503
+ TEvent extends RepairLifecycleApplicationEvent = RepairLifecycleDomEvent,
504
+ > = (
505
+ type: typeof REPAIR_LIFECYCLE_EVENT_TYPE,
506
+ detail: RepairLifecycleEvent,
507
+ options: Readonly<{ bubbles: boolean; composed: boolean }>,
508
+ ) => TEvent;
509
+
510
+ /** Public EventTarget event carrying an immutable RepairLifecycleEvent detail. */
511
+ export const REPAIR_LIFECYCLE_EVENT_TYPE = "repairlifecycle";
512
+
513
+ /** Diagnostic JSON-lines prefix. Never consume logs as a lifecycle API. */
514
+ export const REPAIR_LIFECYCLE_LOG_PREFIX =
515
+ "[MulticastManager] repair-lifecycle ";
516
+
517
+ function createDefaultRepairLifecycleEvent(
518
+ detail: RepairLifecycleEvent,
519
+ options: Readonly<{ bubbles: boolean; composed: boolean }>,
520
+ ): RepairLifecycleDomEvent {
521
+ if (typeof globalThis.CustomEvent === "function") {
522
+ return new CustomEvent<RepairLifecycleEvent>(REPAIR_LIFECYCLE_EVENT_TYPE, {
523
+ detail,
524
+ ...options,
525
+ });
526
+ }
527
+
528
+ const event = new Event(REPAIR_LIFECYCLE_EVENT_TYPE, options);
529
+ Object.defineProperty(event, "detail", {
530
+ value: detail,
531
+ enumerable: true,
532
+ });
533
+ return event as RepairLifecycleDomEvent;
534
+ }
535
+
536
+ function isRecord(value: unknown): value is Record<string, unknown> {
537
+ return value !== null && typeof value === "object" && !Array.isArray(value);
538
+ }
539
+
540
+ function isRepairStreamIdentity(value: unknown): value is RepairStreamIdentity {
541
+ if (!isRecord(value)) return false;
542
+ const packetId = value["packetId"];
543
+ const catalogTrackName = value["catalogTrackName"];
544
+ return (
545
+ Number.isSafeInteger(packetId) &&
546
+ (packetId as number) >= 0 &&
547
+ (catalogTrackName === null ||
548
+ (typeof catalogTrackName === "string" && catalogTrackName.length > 0))
549
+ );
550
+ }
551
+
552
+ function isRepairBlockIdentity(value: unknown): value is RepairBlockIdentity {
553
+ if (!isRecord(value)) return false;
554
+ const sbn = value["sbn"];
555
+ return (
556
+ isRepairStreamIdentity(value) &&
557
+ Number.isSafeInteger(sbn) &&
558
+ (sbn as number) >= 0
559
+ );
560
+ }
561
+
562
+ function isDecoderUnavailableReason(
563
+ value: unknown,
564
+ ): value is FecDecoderUnavailableReason {
565
+ return value === "cleared" || value === "disposed";
566
+ }
567
+
568
+ function isFecFallbackDecoder(value: unknown): value is FecFallbackDecoder {
569
+ return value === "sync" || value === "none";
570
+ }
571
+
572
+ const BLOCK_CLASSES: ReadonlySet<unknown> = new Set(["keyframe", "delta", "unknown", "audio"]);
573
+ const RECLASSIFICATION_EVIDENCE: ReadonlySet<unknown> = new Set([
574
+ "rap",
575
+ "mpu-span",
576
+ "window",
577
+ "classifier-disabled",
578
+ ]);
579
+ const CLASSIFIER_MODES: ReadonlySet<unknown> = new Set(["classifying", "all-protected"]);
580
+ const CLASSIFIER_REASONS: ReadonlySet<unknown> = new Set([
581
+ "framerate-absent",
582
+ "keyframe-cadence-absent",
583
+ "keyframe-interval-not-integral",
584
+ "block-spans-gop",
585
+ "keyframe-interval-not-media-integral",
586
+ "rap-not-mpu-start",
587
+ "stream-geometry-absent",
588
+ "mpu-longer-than-gop",
589
+ "block-not-contiguous",
590
+ "rap-spacing-mismatch",
591
+ "mpu-multiple-fragments",
592
+ "block-wider-than-interleave",
593
+ ]);
594
+ const REPAIR_PRIORITY_REASONS: ReadonlySet<unknown> = new Set([
595
+ "source-priority-absent",
596
+ "source-priority-invalid",
597
+ "repair-priority-absent",
598
+ "repair-priority-invalid",
599
+ ]);
600
+ const GAP_REASONS: Readonly<Record<string, "stall" | "conceal">> = {
601
+ "rap-lost": "stall",
602
+ "rap-unknown": "stall",
603
+ discontinuity: "stall",
604
+ "delta-lost": "conceal",
605
+ "rap-next": "conceal",
606
+ "audio-gap": "conceal",
607
+ "audio-discontinuity": "conceal",
608
+ };
609
+
610
+ function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
611
+ const present = Object.keys(value);
612
+ return present.length === keys.length && keys.every((key) => key in value);
613
+ }
614
+
615
+ function isNonNegativeSafeInteger(value: unknown): boolean {
616
+ return Number.isSafeInteger(value) && (value as number) >= 0;
617
+ }
618
+
619
+ function isSymbolCounts(value: unknown): boolean {
620
+ return (
621
+ isRecord(value) &&
622
+ hasExactKeys(value, ["multicast", "moq"]) &&
623
+ isNonNegativeSafeInteger(value["multicast"]) &&
624
+ isNonNegativeSafeInteger(value["moq"])
625
+ );
626
+ }
627
+
628
+ function isNullableNonNegative(value: unknown): boolean {
629
+ return value === null || (typeof value === "number" && Number.isFinite(value) && value >= 0);
630
+ }
631
+
632
+ /** Runtime guard for observer, DOM-event, and cross-realm consumers. */
633
+ export function isRepairLifecycleEvent(
634
+ value: unknown,
635
+ ): value is RepairLifecycleEvent {
636
+ if (!isRecord(value) || value["version"] !== 2) return false;
637
+ const block = value["block"];
638
+ switch (value["type"]) {
639
+ case "requested": {
640
+ const blockClass = value["blockClass"];
641
+ return (
642
+ hasExactKeys(value, ["version", "type", "block", "blockClass", "priority"]) &&
643
+ isRepairBlockIdentity(block) &&
644
+ BLOCK_CLASSES.has(blockClass) &&
645
+ value["priority"] === repairPriorityForClass(blockClass as BlockClass)
646
+ );
647
+ }
648
+ case "reclassified":
649
+ return (
650
+ hasExactKeys(value, ["version", "type", "block", "from", "to", "evidence"]) &&
651
+ isRepairBlockIdentity(block) &&
652
+ BLOCK_CLASSES.has(value["from"]) &&
653
+ BLOCK_CLASSES.has(value["to"]) &&
654
+ RECLASSIFICATION_EVIDENCE.has(value["evidence"])
655
+ );
656
+ case "recovered":
657
+ return (
658
+ hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) &&
659
+ isRepairBlockIdentity(block) &&
660
+ BLOCK_CLASSES.has(value["blockClass"]) &&
661
+ (value["via"] === "inband" || value["via"] === "quic") &&
662
+ isSymbolCounts(value["symbols"])
663
+ );
664
+ case "failed":
665
+ return (
666
+ hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) &&
667
+ isRepairBlockIdentity(block) &&
668
+ BLOCK_CLASSES.has(value["blockClass"]) &&
669
+ isSymbolCounts(value["symbols"])
670
+ );
671
+ case "repair-preempted":
672
+ case "repair-deferred":
673
+ return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
674
+ case "repair-priority": {
675
+ const blockClass = value["blockClass"];
676
+ const action = value["action"];
677
+ const reason = value["reason"];
678
+ // The action follows from the class: a keyframe/unknown request is
679
+ // sent without the parameter, a delta/audio one is not sent.
680
+ const expected =
681
+ BLOCK_CLASSES.has(blockClass) &&
682
+ repairPriorityForClass(blockClass as BlockClass) === 0
683
+ ? "omitted"
684
+ : "declined";
685
+ return (
686
+ hasExactKeys(value, ["version", "type", "block", "blockClass", "action", "reason"]) &&
687
+ isRepairBlockIdentity(block) &&
688
+ BLOCK_CLASSES.has(blockClass) &&
689
+ action === expected &&
690
+ REPAIR_PRIORITY_REASONS.has(reason) &&
691
+ (action === "omitted") === (reason === "source-priority-absent" || reason === "source-priority-invalid")
692
+ );
693
+ }
694
+ case "classifier": {
695
+ const reason = value["reason"];
696
+ return (
697
+ hasExactKeys(value, ["version", "type", "stream", "mode", "reason"]) &&
698
+ isRepairStreamIdentity(value["stream"]) &&
699
+ CLASSIFIER_MODES.has(value["mode"]) &&
700
+ (reason === null || CLASSIFIER_REASONS.has(reason))
701
+ );
702
+ }
703
+ case "gap": {
704
+ const reason = value["reason"];
705
+ const blocks = value["blocks"];
706
+ return (
707
+ hasExactKeys(value, [
708
+ "version",
709
+ "type",
710
+ "stream",
711
+ "trackKind",
712
+ "action",
713
+ "reason",
714
+ "blocks",
715
+ "missingFrames",
716
+ "missingMs",
717
+ "epoch",
718
+ ]) &&
719
+ isRepairStreamIdentity(value["stream"]) &&
720
+ (value["trackKind"] === "video" || value["trackKind"] === "audio") &&
721
+ typeof reason === "string" &&
722
+ GAP_REASONS[reason] !== undefined &&
723
+ GAP_REASONS[reason] === value["action"] &&
724
+ Array.isArray(blocks) &&
725
+ blocks.every(isNonNegativeSafeInteger) &&
726
+ (value["missingFrames"] === null || isNonNegativeSafeInteger(value["missingFrames"])) &&
727
+ isNullableNonNegative(value["missingMs"]) &&
728
+ isNonNegativeSafeInteger(value["epoch"])
729
+ );
730
+ }
731
+ case "decoder-unavailable":
732
+ return (
733
+ hasExactKeys(value, ["version", "type", "stream", "reason", "fallbackDecoder"]) &&
734
+ isRepairStreamIdentity(value["stream"]) &&
735
+ isDecoderUnavailableReason(value["reason"]) &&
736
+ isFecFallbackDecoder(value["fallbackDecoder"])
737
+ );
738
+ default:
739
+ return false;
740
+ }
741
+ }
742
+
743
+ /**
744
+ * Forward typed repair lifecycle observations through an application-owned
745
+ * EventTarget. The adapter retains no history; the returned function detaches
746
+ * the observer.
747
+ */
748
+ export function forwardRepairLifecycleEvents<
749
+ TEvent extends RepairLifecycleApplicationEvent,
750
+ >(
751
+ source: RepairLifecycleSource,
752
+ target: RepairLifecycleEventTarget<TEvent>,
753
+ options: RepairLifecycleEventOptions<TEvent> & {
754
+ createEvent: RepairLifecycleEventFactory<TEvent>;
755
+ },
756
+ ): () => void;
757
+ export function forwardRepairLifecycleEvents(
758
+ source: RepairLifecycleSource,
759
+ target: EventTarget,
760
+ options?: RepairLifecycleEventOptions,
761
+ ): () => void;
762
+ export function forwardRepairLifecycleEvents(
763
+ source: RepairLifecycleSource,
764
+ target:
765
+ | EventTarget
766
+ | RepairLifecycleEventTarget<RepairLifecycleApplicationEvent>,
767
+ options: RepairLifecycleEventOptions<RepairLifecycleApplicationEvent> = {},
768
+ ): () => void {
769
+ return source.addRepairLifecycleObserver((event) => {
770
+ const eventOptions = {
771
+ bubbles: options.bubbles ?? false,
772
+ composed: options.composed ?? false,
773
+ };
774
+ const forwardedEvent = options.createEvent
775
+ ? options.createEvent(REPAIR_LIFECYCLE_EVENT_TYPE, event, eventOptions)
776
+ : createDefaultRepairLifecycleEvent(event, eventOptions);
777
+ (
778
+ target as RepairLifecycleEventTarget<RepairLifecycleApplicationEvent>
779
+ ).dispatchEvent(forwardedEvent);
780
+ });
781
+ }
782
+
783
+ function repairStreamIdentity(
784
+ packetId: number,
785
+ catalogTrackName?: string,
786
+ ): RepairStreamIdentity {
787
+ if (!Number.isSafeInteger(packetId) || packetId < 0) {
788
+ throw new TypeError("packetId must be a non-negative safe integer");
789
+ }
790
+ if (
791
+ catalogTrackName !== undefined &&
792
+ (typeof catalogTrackName !== "string" || catalogTrackName.length === 0)
793
+ ) {
794
+ throw new TypeError("catalogTrackName must be a non-empty string when provided");
795
+ }
796
+ return {
797
+ packetId,
798
+ catalogTrackName: catalogTrackName ?? null,
799
+ };
800
+ }
801
+
802
+ function repairBlockIdentity(
803
+ packetId: number,
804
+ sbn: number,
805
+ catalogTrackName?: string,
806
+ ): RepairBlockIdentity {
807
+ const stream = repairStreamIdentity(packetId, catalogTrackName);
808
+ if (!Number.isSafeInteger(sbn) || sbn < 0) {
809
+ throw new TypeError("sbn must be a non-negative safe integer");
810
+ }
811
+ return { ...stream, sbn };
812
+ }
813
+
814
+ /**
815
+ * Reject a catalog geometry value that is present but not usable. Absent stays
816
+ * absent — an omitted field is resolved from the previously configured track or
817
+ * left unset — but a supplied non-finite/non-positive value is a catalog defect
818
+ * and must fail at configuration time rather than collapse a derived deadline
819
+ * to ~0 packets later.
820
+ */
821
+ function assertPositiveGeometry(
822
+ label: string,
823
+ value: number | undefined,
824
+ ): void {
825
+ if (value === undefined) return;
826
+ if (!Number.isFinite(value) || value <= 0) {
827
+ throw new Error(
828
+ `[MulticastManager] ${label}=${value}. ` +
829
+ `Derive a positive ${label} from the stream catalog.`,
830
+ );
831
+ }
832
+ }
833
+
834
+ /** Repair-symbol count (P) may legitimately be 0; only reject malformed values. */
835
+ function assertNonNegativeGeometry(
836
+ label: string,
837
+ value: number | undefined,
838
+ ): void {
839
+ if (value === undefined) return;
840
+ if (!Number.isFinite(value) || value < 0) {
841
+ throw new Error(
842
+ `[MulticastManager] ${label}=${value}. ` +
843
+ `Derive a non-negative ${label} from the stream catalog.`,
844
+ );
845
+ }
846
+ }
847
+
848
+ /**
849
+ * One contributor to the stream-global FEC timing reduction.
850
+ *
851
+ * FEC geometry is per-track, but a MulticastManager owns exactly one transport
852
+ * and one router, so the failback watchdog and the router's MFU/reorder timing
853
+ * are stream-global. They are reduced with `max` across every contributor:
854
+ * failback must not fire, and the router must not evict, while ANY configured
855
+ * track's FEC block could still complete.
856
+ */
857
+ interface FecTimingContribution {
858
+ deliveryWindowMs?: number;
859
+ interleaveDepthMs?: number;
860
+ fps?: number;
861
+ k?: number;
862
+ repairSymbols?: number;
863
+ minimumFailbackWindowMs?: number;
864
+ }
865
+
866
+ function fecReorderWindowFrames(
867
+ fecInterleaveDepthMs?: number,
868
+ fps?: number,
869
+ _k?: number,
870
+ _repairSymbols?: number,
871
+ ): number {
872
+ if (!fecInterleaveDepthMs || fecInterleaveDepthMs <= 0 || !fps || fps <= 0) return 0;
873
+ const frameMs = 1000 / fps;
874
+ // Reorder across the FEC block span: fecInterleaveDepthMs IS the full block
875
+ // span (§5.1), so this window admits any FEC-recovered frame from the block
876
+ // without holding frames longer than one block.
877
+ return deriveFecInterleaveDepth(fecInterleaveDepthMs, frameMs);
878
+ }
879
+
880
+ /** Catalog track descriptor for configureMultiTrack(). */
881
+ export interface MultiTrackCatalogTrack {
882
+ name: string;
883
+ altGroup?: number;
884
+ framerate?: number;
885
+ fec?: unknown;
886
+ /** PacketId for testability — in production, learned at subscribe time (Plan 03). */
887
+ packetId?: number;
888
+ /** `"fec-repair"` marks a self-describing repair track (draft-ramadan-moq-fec
889
+ * §6.3). Absent on media tracks and on naming-era catalogs. */
890
+ packaging?: string;
891
+ /** The one source track this repair track carries repair symbols for. Layers
892
+ * 1..n and a keyframe overlay are reachable only through `depends`; layer 0
893
+ * is additionally named by the source's `fec.repairTrack`. */
894
+ depends?: string[];
895
+ /** Base layer index. Absent on a keyframe overlay, which is a separate FEC
896
+ * instance rather than a member of the layer chain. */
897
+ repairLayer?: number;
898
+ /** `"keyframe"` on an overlay track. */
899
+ scope?: string;
900
+ }
901
+
902
+ /** Multi-track catalog shape accepted by configureMultiTrack(). */
903
+ export interface MultiTrackCatalog {
904
+ tracks: MultiTrackCatalogTrack[];
905
+ }
906
+
907
+ /** Creates one stateful synchronous FEC decoder per physical catalog stream. */
908
+ export type WasmFecDecoderFactory = (
909
+ track: Readonly<MultiTrackCatalogTrack>,
910
+ ) => WasmFecDecoder;
911
+
912
+ const DEFAULT_ALT_GROUP = "__default__";
913
+
914
+ type FecDiagnosticsGateway = {
915
+ reportFecDiagnostics?: (snapshot: unknown) => void;
916
+ };
917
+
918
+ /** Active-block tail forwarded to the bridge; mirrors the IWA's bound. */
919
+ const FEC_DIAGNOSTIC_BLOCK_TAIL = 8;
920
+
921
+ /**
922
+ * Project a Worker block snapshot onto the bridge/IWA `subscription_diagnostics`
923
+ * contract. The contract names the per-block repair symbol count `t`; the
924
+ * Worker's `repairCount` is the same quantity (P) under its unambiguous name.
925
+ */
926
+ function projectFecDiagnosticBlock(block: FecBlockSnapshot) {
927
+ return {
928
+ sbn: block.sbn,
929
+ state: block.state,
930
+ sourceReceived: block.sourceReceived,
931
+ repairReceived: block.repairReceived,
932
+ k: block.k,
933
+ t: block.repairCount,
934
+ firstSymbolTs: block.firstSymbolTs,
935
+ lastSymbolTs: block.lastSymbolTs,
936
+ ...(block.completedTs === undefined ? {} : { completedTs: block.completedTs }),
937
+ deadlineTs: block.deadlineTs,
938
+ altaVerified: block.altaVerified,
939
+ relayBlockSigValid: block.relayBlockSigValid,
940
+ };
941
+ }
942
+
943
+ /**
944
+ * Project the Worker track config onto the bridge/IWA contract. Every key
945
+ * below is a named field of that contract (see pim-multicast-gateway
946
+ * `normalizeSubscriptionDiagnostics`); `k`/`t`/`symbolSize` are three
947
+ * independent axes there, so `repairCount` is emitted as `t` and never
948
+ * confused with the symbol size. Worker-internal fields such as
949
+ * `deliveryWindowMs` are not part of the contract and are not forwarded.
950
+ */
951
+ function projectFecDiagnosticConfig(config: FecTrackConfig) {
952
+ return {
953
+ codec: config.codec,
954
+ trackName: config.trackName,
955
+ trackType: config.trackType,
956
+ ...(config.resolution === undefined
957
+ ? {}
958
+ : { resolution: { w: config.resolution.w, h: config.resolution.h } }),
959
+ ...(config.framerate === undefined ? {} : { framerate: config.framerate }),
960
+ ...(config.sampleRate === undefined ? {} : { sampleRate: config.sampleRate }),
961
+ ...(config.algorithm === undefined ? {} : { algorithm: config.algorithm }),
962
+ k: config.k,
963
+ t: config.repairCount,
964
+ symbolSize: config.symbolSize,
965
+ interleaveDepth: config.interleaveDepth,
966
+ interleaveMs: config.interleaveMs,
967
+ fecMode: config.fecMode,
968
+ ...(config.repairTrack === undefined ? {} : { repairTrack: config.repairTrack }),
969
+ altaEnabled: config.altaEnabled,
970
+ relayBlockSigEnabled: config.relayBlockSigEnabled,
971
+ };
972
+ }
973
+
974
+ function publishFecDiagnostics(packetId: number, stats: FecTrackStats): boolean {
975
+ const gateway = (globalThis as typeof globalThis & {
976
+ multicast?: FecDiagnosticsGateway;
977
+ }).multicast;
978
+ if (typeof gateway?.reportFecDiagnostics !== "function") return false;
979
+
980
+ // Keep the control-plane payload bounded and JSON-safe. The Worker snapshot
981
+ // already bounds active blocks; the bridge needs only the current block tail
982
+ // and stable counters, not decoder internals or authentication failure text.
983
+ // The shape is the IWA contract, not the Worker's internal types: spreading
984
+ // FecTrackConfig raw once shipped `repairCount` with no `t`, and the IWA
985
+ // discarded every report ("fec_track.stats.config.t must be a finite
986
+ // non-negative number").
987
+ const snapshot = {
988
+ version: 1,
989
+ packetId,
990
+ observedAt: Date.now(),
991
+ stats: {
992
+ config: projectFecDiagnosticConfig(stats.config),
993
+ sourceSymbols: stats.sourceSymbols,
994
+ repairSymbols: stats.repairSymbols,
995
+ blocksComplete: stats.blocksComplete,
996
+ blocksRecovered: stats.blocksRecovered,
997
+ blocksFailed: stats.blocksFailed,
998
+ // Required by the IWA subscription_diagnostics contract (pim
999
+ // normalizeSubscriptionDiagnostics rejects a report without it). No
1000
+ // fill frame is ever synthesised any more — concealment is the sink's
1001
+ // hold-last-good-frame — so the value is 0 until that contract drops
1002
+ // the field.
1003
+ greenFillFrames: 0,
1004
+ recoveryRate: stats.recoveryRate,
1005
+ liveSbn: stats.liveSbn,
1006
+ blocks: stats.blocks.slice(-FEC_DIAGNOSTIC_BLOCK_TAIL).map(projectFecDiagnosticBlock),
1007
+ interleaveWindowBlocks: stats.interleaveWindowBlocks,
1008
+ avgRecoveryMs: stats.avgRecoveryMs,
1009
+ maxRecoveryMs: stats.maxRecoveryMs,
1010
+ },
1011
+ };
1012
+
1013
+ gateway.reportFecDiagnostics(snapshot);
1014
+ return true;
1015
+ }
1016
+
1017
+ function altGroupKey(track: MultiTrackCatalogTrack): string {
1018
+ return track.altGroup === undefined ? DEFAULT_ALT_GROUP : String(track.altGroup);
1019
+ }
1020
+
1021
+ /**
1022
+ * Every repair track of each source: layer 0 named by the source's
1023
+ * `fec.repairTrack`, plus every self-describing `packaging: "fec-repair"` track
1024
+ * whose `depends` names that source (layers 1..n and a keyframe overlay), per
1025
+ * draft-ramadan-moq-fec §6.3.
1026
+ *
1027
+ * Membership comes from the explicit pointer and from `depends`, never from a
1028
+ * name suffix, so a publisher-chosen name like "parity-alpha" resolves.
1029
+ *
1030
+ * This deliberately does not call `resolveRepairLayers`: that validates the
1031
+ * full layer contract and requires `packaging: "mmtp"` on the source plus a
1032
+ * declared layer-0 repair track, neither of which a `MultiTrackCatalog`
1033
+ * carries. Running it here would throw on every naming-era catalog. Ownership
1034
+ * registration needs membership only; RS_ID offsets and layer ordering are the
1035
+ * decoder's concern, not the router's.
1036
+ */
1037
+ function repairTrackNamesBySource(
1038
+ tracks: readonly MultiTrackCatalogTrack[],
1039
+ ): Map<string, Set<string>> {
1040
+ const bySource = new Map<string, Set<string>>();
1041
+ const add = (source: string, repair: string): void => {
1042
+ if (!source || !repair) return;
1043
+ const names = bySource.get(source) ?? new Set<string>();
1044
+ names.add(repair);
1045
+ bySource.set(source, names);
1046
+ };
1047
+ for (const track of tracks) {
1048
+ // The explicit pointer counts whether or not the source's FEC config is
1049
+ // usable (an unimplemented block profile leaves the track without FEC,
1050
+ // not without its repair track): ownership is membership, not
1051
+ // decodability, so no isFecCatalogConfig gate here.
1052
+ const repairTrack = typeof track.fec === "object" && track.fec !== null
1053
+ ? (track.fec as { readonly repairTrack?: unknown }).repairTrack
1054
+ : undefined;
1055
+ if (typeof repairTrack === "string") add(track.name, repairTrack);
1056
+ if (track.packaging === "fec-repair" && Array.isArray(track.depends) && track.depends.length === 1) {
1057
+ add(track.depends[0]!, track.name);
1058
+ }
1059
+ }
1060
+ return bySource;
1061
+ }
1062
+
1063
+ export class MulticastManager {
1064
+ readonly #fec: FECManager;
1065
+ readonly #router: MmtpRouter;
1066
+ readonly #transport: MulticastTransport<MmtpIngressContext>;
1067
+ #reportedFecDiagnosticsFailure = false;
1068
+
1069
+ // ── Stream-global FEC timing reduction ──
1070
+ //
1071
+ // FEC geometry is per-track; the transport failback watchdog and the router's
1072
+ // MFU/reorder timing are stream-global (one transport, one router). Both
1073
+ // configuration entry points feed the same reduction so neither can silently
1074
+ // clip the other: configureFec() supplies the baseline, configureTrackFec()
1075
+ // supplies one entry per track, and #applyStreamGlobalFecTiming() takes the
1076
+ // max across all of them.
1077
+ #streamFecBaseline?: FecTimingContribution;
1078
+ readonly #trackFecTiming = new Map<number, FecTimingContribution>();
1079
+
1080
+ // ── Phase 14: multi-track state (D-06, D-07, D-17, D-26, D-28) ──
1081
+
1082
+ /** Maps altGroup → track names sharing that altGroup. */
1083
+ #switchingSets: Map<number, string[]> = new Map();
1084
+
1085
+ /** Repair packetIds that should not get their own FEC decoder (they ARE the repair source). */
1086
+ #repairPacketIds: Set<number> = new Set();
1087
+
1088
+ /** Tracks physical-stream FEC blocks with an outstanding repair fetch. */
1089
+ #repairInFlight: Set<string> = new Set();
1090
+
1091
+ /** Causal repair events; observers own any retention they require. */
1092
+ #repairLifecycleObservers = new Set<RepairLifecycleObserver>();
1093
+ readonly #logRepairLifecycle: boolean;
1094
+
1095
+ #trackResetObservers = new Set<
1096
+ (packetId: number, catalogTrackName: string) => void
1097
+ >();
1098
+
1099
+ /** Callback fired when a repair fetch should be issued for a block. */
1100
+ #onRepairSubscribeCb: RepairSubscribeCallback | null = null;
1101
+
1102
+ /** Keyframe-protected repair policy counters per catalog track. */
1103
+ #blockPolicyStats = new Map<string, BlockPolicyStats>();
1104
+
1105
+ /** The staged in-place rendition switch, if any. */
1106
+ #renditionSwitch: ActiveRenditionSwitch | null = null;
1107
+
1108
+ constructor(options?: MulticastManagerOptions) {
1109
+ this.#logRepairLifecycle = options?.logRepairLifecycle === true;
1110
+ this.#fec = new FECManager();
1111
+ this.#fec.addFecStatsObserver((packetId, stats) => {
1112
+ try {
1113
+ if (publishFecDiagnostics(packetId, stats)) {
1114
+ this.#reportedFecDiagnosticsFailure = false;
1115
+ }
1116
+ } catch (error) {
1117
+ if (!this.#reportedFecDiagnosticsFailure) {
1118
+ this.#reportedFecDiagnosticsFailure = true;
1119
+ console.warn('[MulticastManager] Failed to publish FEC diagnostics:', error);
1120
+ }
1121
+ }
1122
+ });
1123
+ this.#router = new MmtpRouter({
1124
+ fecManager: this.#fec,
1125
+ mfuTimeoutMs: options?.mfuTimeoutMs,
1126
+ reassemblyPolicy: options?.reassemblyPolicy,
1127
+ reassembler: options?.reassembler,
1128
+ maxBufferedMfus: options?.maxBufferedMfus,
1129
+ manifestVerifier: options?.manifestVerifier,
1130
+ manifestVerifierOwnership: options?.manifestVerifierOwnership,
1131
+ resolveManifestIdentity: options?.resolveManifestIdentity,
1132
+ resolveManifestIdentityForRoute: options?.resolveManifestIdentityForRoute,
1133
+ // The router has reset its own state for the stream; reset the rest.
1134
+ onPublisherRestart: (packetId, catalogTrackName) => {
1135
+ this.#resetStreamOutsideRouter(packetId, catalogTrackName);
1136
+ },
1137
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
1138
+ const pathCount = this.#fec.blockPathCount(
1139
+ sbn,
1140
+ packetId,
1141
+ catalogTrackName,
1142
+ );
1143
+ const stats = this.#statsFor(packetId, catalogTrackName);
1144
+ if (blockClass === "delta") stats.deltaBlocksFailed++;
1145
+ else if (blockClass === "audio") stats.audioBlocksFailed++;
1146
+ else stats.keyframeBlocksFailed++;
1147
+ this.#emitRepairLifecycle({
1148
+ version: 2,
1149
+ type: "failed",
1150
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
1151
+ blockClass,
1152
+ symbols: {
1153
+ multicast: pathCount?.multicastSymbols ?? 0,
1154
+ moq: pathCount?.moqSymbols ?? 0,
1155
+ },
1156
+ });
1157
+ },
1158
+ onFrameGap: (decision) => {
1159
+ const stats = this.#statsFor(
1160
+ decision.stream.packetId,
1161
+ decision.stream.catalogTrackName ?? undefined,
1162
+ );
1163
+ if (decision.action === "stall") {
1164
+ stats.stalls++;
1165
+ } else {
1166
+ stats.concealedGaps++;
1167
+ stats.concealedBlocks += decision.blocks.length;
1168
+ if (decision.trackKind === "audio") {
1169
+ stats.concealedAudioMs += decision.missingMs ?? 0;
1170
+ } else {
1171
+ stats.concealedFrames += decision.missingFrames ?? 0;
1172
+ }
1173
+ }
1174
+ this.#emitRepairLifecycle(decision);
1175
+ },
1176
+ });
1177
+ this.#transport = new MulticastTransport<MmtpIngressContext>((packet, ingress) => {
1178
+ this.#router.feedPacket(packet, "multicast", undefined, ingress);
1179
+ });
1180
+ // Each joined subscription declares how it delivers packets. An ordered
1181
+ // relay decides FEC block fate by stream order instead of the datagram
1182
+ // inactivity deadline (see MulticastSymbolDelivery in fec-manager).
1183
+ this.#transport.onDelivery((delivery) => {
1184
+ this.#fec.setMulticastSymbolDelivery(delivery);
1185
+ });
1186
+
1187
+ // Worker-path FEC recovery: route recovered source-symbol bytes through
1188
+ // MmtpRouter so MFU reassembly + dedup runs. Without this wiring the
1189
+ // FecWorkerClient's recovered frames fire FECManager.onBlockRecovered
1190
+ // into a null callback and VideoDecoder never sees a real frame.
1191
+ this.#fec.onBlockRecovered = (sbn, packetId, data, meta, recoveredTrackName) => {
1192
+ const recovered = new Uint8Array(data);
1193
+ const catalogTrackName = recoveredTrackName
1194
+ ?? this.#fec.catalogTrackNameForBlock(sbn, packetId);
1195
+ if (catalogTrackName === undefined) {
1196
+ this.#router.routeRecoveredSymbol(sbn, recovered, packetId, meta.esi);
1197
+ } else {
1198
+ this.#router.routeRecoveredSymbol(
1199
+ sbn,
1200
+ recovered,
1201
+ packetId,
1202
+ meta.esi,
1203
+ catalogTrackName,
1204
+ );
1205
+ }
1206
+ };
1207
+
1208
+ // D-28: release the in-flight repair slot when a repair-requested block
1209
+ // resolves (completes, recovers, or fails), and emit the gate log line.
1210
+ // The request-side bridge (FECManager.onRepairNeeded) is wired in
1211
+ // onRepairSubscribe() so repair deadlines only arm once a player has
1212
+ // registered a fetcher — consumers without D-28 pay no timer cost.
1213
+ this.#fec.onRepairResolved = (sbn, packetId, _outcome, catalogTrackName) => {
1214
+ this.clearRepairForBlock(sbn, packetId, catalogTrackName);
1215
+ };
1216
+ // Every block that could not complete from its first-arrival source
1217
+ // symbols and completed anyway reports `recovered` exactly once.
1218
+ this.#fec.onBlockRepaired = (sbn, packetId, catalogTrackName, blockClass, via) => {
1219
+ const pathCount = this.#fec.blockPathCount(sbn, packetId, catalogTrackName);
1220
+ const stats = this.#statsFor(packetId, catalogTrackName);
1221
+ if (blockClass === "delta") {
1222
+ if (via === "quic") stats.deltaBlocksRecoveredQuic++;
1223
+ else stats.deltaBlocksRecoveredInband++;
1224
+ } else if (blockClass === "audio") {
1225
+ if (via === "quic") stats.audioBlocksRecoveredQuic++;
1226
+ else stats.audioBlocksRecoveredInband++;
1227
+ } else if (via === "quic") {
1228
+ stats.keyframeBlocksRecoveredQuic++;
1229
+ } else {
1230
+ stats.keyframeBlocksRecoveredInband++;
1231
+ }
1232
+ this.#emitRepairLifecycle({
1233
+ version: 2,
1234
+ type: "recovered",
1235
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
1236
+ blockClass,
1237
+ via,
1238
+ symbols: {
1239
+ multicast: pathCount?.multicastSymbols ?? 0,
1240
+ moq: pathCount?.moqSymbols ?? 0,
1241
+ },
1242
+ });
1243
+ };
1244
+ this.#fec.onBlockReclassified = (sbn, packetId, catalogTrackName, from, to, evidence) => {
1245
+ this.#emitRepairLifecycle({
1246
+ version: 2,
1247
+ type: "reclassified",
1248
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
1249
+ from,
1250
+ to,
1251
+ evidence,
1252
+ });
1253
+ };
1254
+ this.#fec.onClassifierMode = (packetId, catalogTrackName, mode, reason) => {
1255
+ const stats = this.#statsFor(packetId, catalogTrackName);
1256
+ stats.classifierMode = mode;
1257
+ stats.classifierReason = reason;
1258
+ this.#emitRepairLifecycle({
1259
+ version: 2,
1260
+ type: "classifier",
1261
+ stream: repairStreamIdentity(packetId, catalogTrackName),
1262
+ mode,
1263
+ reason,
1264
+ });
1265
+ };
1266
+ this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
1267
+ this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
1268
+ };
1269
+ this.#fec.onDecoderUnavailable = (event) => {
1270
+ this.#emitRepairLifecycle({
1271
+ version: 2,
1272
+ type: "decoder-unavailable",
1273
+ stream: repairStreamIdentity(event.packetId, event.catalogTrackName),
1274
+ reason: event.reason,
1275
+ fallbackDecoder: event.fallbackDecoder,
1276
+ });
1277
+ };
1278
+ }
1279
+
1280
+ // ---------------------------------------------------------------------------
1281
+ // Decomposed component accessors (for new code)
1282
+ // ---------------------------------------------------------------------------
1283
+
1284
+ get fecManager(): FECManager {
1285
+ return this.#fec;
1286
+ }
1287
+ get router(): MmtpRouter {
1288
+ return this.#router;
1289
+ }
1290
+ get transport(): MulticastTransport<MmtpIngressContext> {
1291
+ return this.#transport;
1292
+ }
1293
+
1294
+ // ---------------------------------------------------------------------------
1295
+ // Stats
1296
+ // ---------------------------------------------------------------------------
1297
+
1298
+ get reassembler() {
1299
+ return this.#router.reassembler;
1300
+ }
1301
+ get diagnostics() {
1302
+ return {
1303
+ ...this.#router.getDiagnostics(),
1304
+ _fec: this.#fec.diagnostics,
1305
+ };
1306
+ }
1307
+ get stats() {
1308
+ return this.#transport.stats;
1309
+ }
1310
+
1311
+ /**
1312
+ * See MulticastTransport.lastJoinOutcome: how the newest join() to resolve
1313
+ * did, and the typed reason it resolved false. join() here adds no false
1314
+ * path of its own, so every false it returns is named there; a join() that
1315
+ * rejects (catalog FEC configuration that configureFec refuses, for one)
1316
+ * records nothing.
1317
+ */
1318
+ get lastJoinOutcome(): MulticastJoinOutcome | undefined {
1319
+ return this.#transport.lastJoinOutcome;
1320
+ }
1321
+ /** See MulticastTransport.joinStats: join() calls by how they resolved. */
1322
+ get joinStats(): MulticastJoinStats {
1323
+ return this.#transport.joinStats;
1324
+ }
1325
+
1326
+ /**
1327
+ * Accepted bytes for these MMTP packet_ids, cumulative like
1328
+ * `stats.bytesReceived`; see MulticastTransport.bytesReceivedForPacketIds.
1329
+ * Scopes an ABR throughput sample to the active tier when the join admits
1330
+ * more packet_ids than that tier's. Monotonic only while the set is fixed:
1331
+ * re-baseline when the queried set changes (e.g. on a tier switch).
1332
+ */
1333
+ bytesReceivedForPacketIds(packetIds: ReadonlySet<number>): number {
1334
+ return this.#transport.bytesReceivedForPacketIds(packetIds);
1335
+ }
1336
+
1337
+ get fecStats() {
1338
+ return this.#fec.fecStats;
1339
+ }
1340
+
1341
+ /** The raw WASM decoder for stats access */
1342
+ get wasmDecoder() {
1343
+ return this.#fec.wasmDecoder;
1344
+ }
1345
+
1346
+ // ---------------------------------------------------------------------------
1347
+ // FEC configuration (delegates to FECManager)
1348
+ // ---------------------------------------------------------------------------
1349
+
1350
+ setFecDecoder(
1351
+ packetId: number,
1352
+ client: WasmFecDecoder,
1353
+ k: number,
1354
+ trackType: "video" | "audio" = "video",
1355
+ config?: FECManagerConfig,
1356
+ catalogTrackName?: string,
1357
+ ) {
1358
+ const fecConfig = { ...config, k, trackKind: config?.trackKind ?? trackType };
1359
+ this.#fec.setFecDecoder(packetId, client, k, fecConfig, catalogTrackName);
1360
+ this.#configureTrackMapper(packetId, fecConfig);
1361
+ this.#router.setPacketIdType(packetId, trackType);
1362
+ }
1363
+
1364
+ /**
1365
+ * Register a Worker-backed FEC decoder for a specific packetId (track).
1366
+ * Worker-backed tracks decode asynchronously — recovered frames arrive via
1367
+ * FECManager.onBlockRecovered callback instead of feedSourceSymbol return value.
1368
+ */
1369
+ setFecWorker(
1370
+ packetId: number,
1371
+ client: FecWorkerClient,
1372
+ trackType: "video" | "audio",
1373
+ config: FECManagerConfig,
1374
+ catalogTrackName?: string,
1375
+ ): void {
1376
+ this.#fec.setFecWorker(
1377
+ packetId,
1378
+ client,
1379
+ { ...config, trackKind: config.trackKind ?? trackType },
1380
+ catalogTrackName,
1381
+ );
1382
+ this.#configureTrackMapper(packetId, config);
1383
+ this.#router.setPacketIdType(packetId, trackType);
1384
+ }
1385
+
1386
+ /**
1387
+ * Stop routing a stream's symbols to its Worker decoder. Returns false when
1388
+ * none is registered; on success one `decoder-unavailable` repair lifecycle
1389
+ * event with reason 'cleared' reaches every observer, carrying whether a
1390
+ * synchronous WASM decoder still serves the stream. The packet mapping and
1391
+ * track type are untouched: the track still exists, it just has no Worker
1392
+ * decoder. Call this before disposing the client.
1393
+ */
1394
+ clearFecWorker(packetId: number, catalogTrackName?: string): boolean {
1395
+ return this.#fec.clearFecWorker(packetId, catalogTrackName);
1396
+ }
1397
+
1398
+ /** Register callback for Worker-level FecTrackStats updates. */
1399
+ setOnFecStatsUpdate(
1400
+ cb: (packetId: number, stats: FecTrackStats) => void,
1401
+ ): void {
1402
+ this.#fec.onFecStatsUpdate = cb;
1403
+ }
1404
+
1405
+ setFramerate(fps: number) {
1406
+ this.#router.setFramerate(fps);
1407
+ }
1408
+
1409
+ #configureTrackMapper(packetId: number, config: FECManagerConfig): void {
1410
+ const k = config.k;
1411
+ const interleaveMs = config.interleaveDepthMs;
1412
+ const fps = config.fps;
1413
+ const blockProfile = config.blockProfile;
1414
+ if (blockProfile !== undefined && k && k > 0 && interleaveMs && interleaveMs > 0 && fps && fps > 0) {
1415
+ this.#router.setFecMapper(
1416
+ new FecBlockMapper({
1417
+ blockProfile,
1418
+ k,
1419
+ interleaveDepthMs: interleaveMs,
1420
+ gopDurationMs: 1000 / fps,
1421
+ }),
1422
+ packetId,
1423
+ );
1424
+ }
1425
+ }
1426
+
1427
+ /**
1428
+ * Reduce every registered FEC timing contributor to the stream-global
1429
+ * deadlines and apply them to the single transport and single router.
1430
+ *
1431
+ * `max`, not `min` or last-write-wins: a narrower track must never pull the
1432
+ * failback watchdog or the router's reorder window in under a wider track's
1433
+ * still-completable FEC block. Recomputed on every registration so a track
1434
+ * that arrives late widens the stream rather than being clipped by it.
1435
+ */
1436
+ #applyStreamGlobalFecTiming(): void {
1437
+ const contributions: FecTimingContribution[] = [
1438
+ ...(this.#streamFecBaseline ? [this.#streamFecBaseline] : []),
1439
+ ...this.#trackFecTiming.values(),
1440
+ ];
1441
+ if (contributions.length === 0) return;
1442
+
1443
+ let deliveryWindowMs: number | undefined;
1444
+ let minimumFailbackWindowMs: number | undefined;
1445
+ let mfuTimeoutMs: number | undefined;
1446
+ let reorderWindowFrames: number | undefined;
1447
+
1448
+ for (const c of contributions) {
1449
+ if (c.deliveryWindowMs !== undefined) {
1450
+ deliveryWindowMs = Math.max(deliveryWindowMs ?? 0, c.deliveryWindowMs);
1451
+ }
1452
+ if (c.minimumFailbackWindowMs !== undefined) {
1453
+ minimumFailbackWindowMs = Math.max(
1454
+ minimumFailbackWindowMs ?? 0,
1455
+ c.minimumFailbackWindowMs,
1456
+ );
1457
+ }
1458
+ // Only a valid §5.1 ms interleave may drive router timing. A sub-floor
1459
+ // value is a raw frame count (no fps to convert with) and would collapse
1460
+ // the MFU timeout to ~0 and the reorder window to a single frame; skip
1461
+ // the derivation rather than clamp it, leaving previously-configured
1462
+ // router timing untouched.
1463
+ const interleaveOk =
1464
+ c.interleaveDepthMs !== undefined &&
1465
+ c.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS;
1466
+ if (interleaveOk && c.deliveryWindowMs) {
1467
+ mfuTimeoutMs = Math.max(mfuTimeoutMs ?? 0, c.deliveryWindowMs);
1468
+ }
1469
+ if (interleaveOk && c.fps && c.fps > 0) {
1470
+ reorderWindowFrames = Math.max(
1471
+ reorderWindowFrames ?? 0,
1472
+ fecReorderWindowFrames(
1473
+ c.interleaveDepthMs,
1474
+ c.fps,
1475
+ c.k,
1476
+ c.repairSymbols,
1477
+ ),
1478
+ );
1479
+ }
1480
+ }
1481
+
1482
+ const failbackWindowMs =
1483
+ deliveryWindowMs === undefined
1484
+ ? minimumFailbackWindowMs
1485
+ : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
1486
+ if (failbackWindowMs !== undefined) {
1487
+ this.#transport.setFailbackWindowMs(failbackWindowMs);
1488
+ }
1489
+ if (mfuTimeoutMs !== undefined) {
1490
+ this.#router.setMfuTimeoutMs(mfuTimeoutMs);
1491
+ }
1492
+ if (reorderWindowFrames !== undefined) {
1493
+ this.#router.setReorderWindow(reorderWindowFrames);
1494
+ }
1495
+ }
1496
+
1497
+ /**
1498
+ * Configure one track's FEC geometry, block mapper, and block-inactivity
1499
+ * deadline from that track's own catalog values, then re-reduce the
1500
+ * stream-global deadlines across every registered track.
1501
+ *
1502
+ * This is the packet-specific replacement for the global `configureFec`
1503
+ * side effects: per-track concerns stay per-track, and the genuinely
1504
+ * stream-global ones (transport failback, router MFU timeout, router reorder
1505
+ * window) become an explicit max reduction instead of a last-caller-wins race
1506
+ * in which whichever track configured last silently set the whole stream's
1507
+ * timing.
1508
+ *
1509
+ * `catalogTrackName` scopes the block-classifier geometry (kind, fps,
1510
+ * interleave, cadence) to that one stream. Pass it whenever ABR rungs can
1511
+ * share this packetId: each rung then classifies with its own framerate
1512
+ * and GOP, and a rung on the packetId that was never configured this way
1513
+ * runs all-protected (`stream-geometry-absent`) instead of borrowing a
1514
+ * sibling's geometry. K, T and the delivery timing stay per packetId.
1515
+ */
1516
+ configureTrackFec(
1517
+ packetId: number,
1518
+ config: Pick<
1519
+ MulticastEndpointConfig,
1520
+ | "fecBlockProfile"
1521
+ | "fecK"
1522
+ | "fecRepairSymbols"
1523
+ | "fecSymbolSize"
1524
+ | "fecInterleaveDepthMs"
1525
+ | "fecReorderToleranceMs"
1526
+ | "fps"
1527
+ | "bandwidth"
1528
+ | "minimumFailbackWindowMs"
1529
+ | "trackKind"
1530
+ | "codec"
1531
+ | "timescale"
1532
+ | "keyframeIntervalTicks"
1533
+ | "keyframeIntervalMs"
1534
+ >,
1535
+ catalogTrackName?: string,
1536
+ ): void {
1537
+ if (catalogTrackName !== undefined && catalogTrackName.length === 0) {
1538
+ throw new Error(
1539
+ `[MulticastManager] configureTrackFec(${packetId}) catalogTrackName must be non-empty when given`,
1540
+ );
1541
+ }
1542
+ if (config.fecK === undefined || config.fecInterleaveDepthMs === undefined) {
1543
+ throw new Error(
1544
+ `[MulticastManager] configureTrackFec(${packetId}) requires fecK and ` +
1545
+ "fecInterleaveDepthMs. Derive the per-track FEC geometry from the " +
1546
+ "stream catalog.",
1547
+ );
1548
+ }
1549
+ const blockProfile = parseFecBlockProfile(
1550
+ config.fecBlockProfile,
1551
+ `[MulticastManager] configureTrackFec(${packetId}) fecBlockProfile`,
1552
+ );
1553
+ assertPositiveGeometry("fecK", config.fecK);
1554
+ assertPositiveGeometry("fecInterleaveDepthMs", config.fecInterleaveDepthMs);
1555
+ assertPositiveGeometry("fecSymbolSize", config.fecSymbolSize);
1556
+ assertPositiveGeometry("fps", config.fps);
1557
+ assertPositiveGeometry("bandwidth", config.bandwidth);
1558
+ assertPositiveGeometry(
1559
+ "minimumFailbackWindowMs",
1560
+ config.minimumFailbackWindowMs,
1561
+ );
1562
+ assertPositiveGeometry("timescale", config.timescale);
1563
+ assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
1564
+ assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
1565
+ assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
1566
+ // A tolerance is the network path's allowance, added to the encoder's
1567
+ // span. These are public entry points: the catalog parser validates what it
1568
+ // parses, but a direct caller reaches this arithmetic without passing
1569
+ // through it. A negative value silently *shortens* the delivery window
1570
+ // below the signaled span, and Infinity/NaN yields a window no block can
1571
+ // ever miss -- the eviction bound stops bounding. Reuse the shared
1572
+ // non-negative guard rather than an inline check: undefined must stay
1573
+ // undefined (absent means the encoder never signaled one, and must not be
1574
+ // defaulted), while a declared 0 is a real value that has to survive.
1575
+ assertNonNegativeGeometry(
1576
+ "fecReorderToleranceMs",
1577
+ config.fecReorderToleranceMs,
1578
+ );
1579
+
1580
+ // Same derivation as the stream-global path, but from THIS track's
1581
+ // geometry. FECManager already stores a per-track timeoutMs
1582
+ // (configureTrack/timeoutMsForPacket); it just never had the repair-symbol
1583
+ // and bandwidth inputs needed to compute one.
1584
+ const deliveryWindowMs =
1585
+ config.fecInterleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS
1586
+ ? computeFecDeliveryWindowMs({
1587
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1588
+ sourceSymbols: config.fecK,
1589
+ repairSymbols: config.fecRepairSymbols,
1590
+ symbolSize: config.fecSymbolSize,
1591
+ mediaUnitsPerSecond: config.fps,
1592
+ bandwidthBps: config.bandwidth,
1593
+ jitterBufferMs: config.fecReorderToleranceMs,
1594
+ })
1595
+ : undefined;
1596
+
1597
+ // The block classifier's geometry comes from the raw catalog cadence
1598
+ // fields; a track whose media kind is not known yet classifies fail-closed.
1599
+ const trackKind = config.trackKind ?? this.#router.trackKindFor(packetId);
1600
+ const geometry = trackKind === undefined
1601
+ ? undefined
1602
+ : deriveBlockClassifierGeometry({
1603
+ trackKind,
1604
+ framerate: config.fps,
1605
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1606
+ timescale: config.timescale,
1607
+ keyframeIntervalTicks: config.keyframeIntervalTicks,
1608
+ keyframeIntervalMs: config.keyframeIntervalMs,
1609
+ });
1610
+ const fecConfig: FECManagerConfig = {
1611
+ blockProfile,
1612
+ k: config.fecK,
1613
+ symbolSize: config.fecSymbolSize,
1614
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1615
+ fps: config.fps,
1616
+ timeoutMs: deliveryWindowMs,
1617
+ ...(trackKind === undefined ? {} : { trackKind }),
1618
+ ...(config.codec === undefined ? {} : { codec: config.codec }),
1619
+ ...(geometry === undefined ? {} : { geometry }),
1620
+ };
1621
+ this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
1622
+ this.#configureTrackMapper(packetId, fecConfig);
1623
+
1624
+ this.#trackFecTiming.set(packetId, {
1625
+ deliveryWindowMs,
1626
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1627
+ fps: config.fps,
1628
+ k: config.fecK,
1629
+ repairSymbols: config.fecRepairSymbols,
1630
+ minimumFailbackWindowMs: config.minimumFailbackWindowMs,
1631
+ });
1632
+ this.#applyStreamGlobalFecTiming();
1633
+ }
1634
+
1635
+ configureFec(
1636
+ config: Pick<
1637
+ MulticastEndpointConfig,
1638
+ | "fecBlockProfile"
1639
+ | "fecK"
1640
+ | "fecRepairSymbols"
1641
+ | "fecSymbolSize"
1642
+ | "fecInterleaveDepthMs"
1643
+ | "fecReorderToleranceMs"
1644
+ | "fps"
1645
+ | "bandwidth"
1646
+ | "minimumFailbackWindowMs"
1647
+ >,
1648
+ ) {
1649
+ const minimumFailbackWindowMs = config.minimumFailbackWindowMs;
1650
+ if (
1651
+ minimumFailbackWindowMs !== undefined &&
1652
+ (!Number.isFinite(minimumFailbackWindowMs) || minimumFailbackWindowMs <= 0)
1653
+ ) {
1654
+ throw new Error(
1655
+ `[MulticastManager] minimumFailbackWindowMs=${minimumFailbackWindowMs}. ` +
1656
+ "Derive a positive failback floor from the stream catalog.",
1657
+ );
1658
+ }
1659
+ // A tolerance is the network path's allowance, added to the encoder's
1660
+ // span. These are public entry points: the catalog parser validates what it
1661
+ // parses, but a direct caller reaches this arithmetic without passing
1662
+ // through it. A negative value silently *shortens* the delivery window
1663
+ // below the signaled span, and Infinity/NaN yields a window no block can
1664
+ // ever miss -- the eviction bound stops bounding. Reuse the shared
1665
+ // non-negative guard rather than an inline check: undefined must stay
1666
+ // undefined (absent means the encoder never signaled one, and must not be
1667
+ // defaulted), while a declared 0 is a real value that has to survive.
1668
+ assertNonNegativeGeometry(
1669
+ "fecReorderToleranceMs",
1670
+ config.fecReorderToleranceMs,
1671
+ );
1672
+ const deliveryWindowMs =
1673
+ config.fecK &&
1674
+ config.fecK > 0 &&
1675
+ config.fecInterleaveDepthMs &&
1676
+ config.fecInterleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS
1677
+ ? computeFecDeliveryWindowMs({
1678
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1679
+ sourceSymbols: config.fecK,
1680
+ repairSymbols: config.fecRepairSymbols,
1681
+ symbolSize: config.fecSymbolSize,
1682
+ mediaUnitsPerSecond: config.fps,
1683
+ bandwidthBps: config.bandwidth,
1684
+ jitterBufferMs: config.fecReorderToleranceMs,
1685
+ })
1686
+ : undefined;
1687
+ this.#fec.configure({
1688
+ k: config.fecK,
1689
+ symbolSize: config.fecSymbolSize,
1690
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1691
+ fps: config.fps,
1692
+ timeoutMs: deliveryWindowMs,
1693
+ });
1694
+ // External-feed consumers own the multicast socket and call feedPacket()
1695
+ // directly, so they never enter join(). Configure the transport watchdog
1696
+ // here where both transport-owned and external-feed paths share the same
1697
+ // catalog-derived FEC timing.
1698
+ //
1699
+ // This call supplies the stream-global BASELINE contribution. Any track
1700
+ // registered via configureTrackFec() participates in the same max
1701
+ // reduction, so a per-track window can only widen these deadlines, never
1702
+ // narrow them below what this baseline already guarantees.
1703
+ this.#streamFecBaseline = {
1704
+ deliveryWindowMs,
1705
+ interleaveDepthMs: config.fecInterleaveDepthMs,
1706
+ fps: config.fps,
1707
+ k: config.fecK,
1708
+ repairSymbols: config.fecRepairSymbols,
1709
+ minimumFailbackWindowMs,
1710
+ };
1711
+ this.#applyStreamGlobalFecTiming();
1712
+ // Wire the stream-global FecBlockMapper to MmtpRouter. Under iso-ssbg1-v1
1713
+ // (the only profile) the mapper locates no source symbol: a source is
1714
+ // placed only once a repair states its block (SS_Start, SSB_length), and
1715
+ // FecBlockMapper.fromSsId refuses every FEC stream. The router reads the
1716
+ // mapper only for the stream's block profile and K_max when no FEC
1717
+ // manager answers for the packet.
1718
+ //
1719
+ // gopDurationMs is the per-frame interval (1000/fps), never the
1720
+ // interleaveDepthMs: the mapper derives its interleave depth D from their
1721
+ // ratio, and passing interleaveDepthMs collapses D to 1 (BLO-3323 L14).
1722
+ const k = config.fecK;
1723
+ const interleaveMs = config.fecInterleaveDepthMs;
1724
+ const fps = config.fps;
1725
+ // The stream-global mapper exists only for a stream whose catalog names a
1726
+ // block profile; parseFecBlockProfile refuses the retired k-padded-v1.
1727
+ const blockProfile = config.fecBlockProfile === undefined
1728
+ ? undefined
1729
+ : parseFecBlockProfile(config.fecBlockProfile, "[MulticastManager] configureFec fecBlockProfile");
1730
+ if (blockProfile !== undefined && k && k > 0 && interleaveMs && interleaveMs > 0 && fps && fps > 0) {
1731
+ const mapper = new FecBlockMapper({
1732
+ blockProfile,
1733
+ k,
1734
+ interleaveDepthMs: interleaveMs,
1735
+ gopDurationMs: 1000 / fps,
1736
+ });
1737
+ this.#router.setFecMapper(mapper);
1738
+ }
1739
+ }
1740
+
1741
+ // ---------------------------------------------------------------------------
1742
+ // Track configuration (delegates to MmtpRouter)
1743
+ // ---------------------------------------------------------------------------
1744
+
1745
+ // Track type discovery callback — fires when setPacketIdType is called.
1746
+ // Players wire this to MediaRouter.registerTrackTypeFromInit() for
1747
+ // init data authority (authoritative until next catalog update).
1748
+ #onTrackTypeDiscovered:
1749
+ | ((packetId: number, trackType: "video" | "audio") => void)
1750
+ | null = null;
1751
+
1752
+ /** Register callback for track type discovery (from init data / inline signaling). */
1753
+ onTrackTypeDiscovered(
1754
+ cb: (packetId: number, trackType: "video" | "audio") => void,
1755
+ ): void {
1756
+ this.#onTrackTypeDiscovered = cb;
1757
+ }
1758
+
1759
+ setPacketIdType(packetId: number, trackType: "video" | "audio") {
1760
+ this.#router.setPacketIdType(packetId, trackType);
1761
+ this.#onTrackTypeDiscovered?.(packetId, trackType);
1762
+ }
1763
+
1764
+ /**
1765
+ * Set the keyframe loss timeout on the inner MmtpRouter (Phase 13).
1766
+ * Applies only to tracks WITHOUT FEC: an FEC track never arms the timer,
1767
+ * because its vanished blocks resolve through catalog-derived block
1768
+ * deadlines and the release gate's stall decision.
1769
+ * Must be called BEFORE setPacketIdType('video'). A reader is passed
1770
+ * through; see MmtpRouter.setKeyframeLostTimeoutMs.
1771
+ */
1772
+ setKeyframeLostTimeoutMs(ms: number | (() => number)): void {
1773
+ this.#router.setKeyframeLostTimeoutMs(ms);
1774
+ }
1775
+
1776
+ setMfuTimeoutMs(ms: number): void {
1777
+ this.#router.setMfuTimeoutMs(ms);
1778
+ }
1779
+
1780
+ setTrackCodec(packetId: number, codec: string) {
1781
+ this.#router.setTrackCodec(packetId, codec);
1782
+ // Never configure an FEC track by side effect: only an already
1783
+ // configured FEC track learns its codec here.
1784
+ if (this.#fec.isTrackConfigured(packetId)) {
1785
+ this.#fec.configureTrack(packetId, { codec });
1786
+ }
1787
+ }
1788
+
1789
+ // ---------------------------------------------------------------------------
1790
+ // Callbacks (delegates to MmtpRouter)
1791
+ // ---------------------------------------------------------------------------
1792
+
1793
+ onVideoFrame(cb: FrameCallback) {
1794
+ this.#router.onVideoFrame(cb);
1795
+ }
1796
+ onAudioFrame(cb: FrameCallback) {
1797
+ this.#router.onAudioFrame(cb);
1798
+ }
1799
+ onTrackFrame(packetId: number, cb: FrameCallback) {
1800
+ this.#router.onTrackFrame(packetId, cb);
1801
+ }
1802
+ onTrackPacket(packetId: number, cb: TrackPacketCallback) {
1803
+ this.#router.onTrackPacket(packetId, cb);
1804
+ }
1805
+ /** @deprecated Use onTrackInit(packetId, cb); see MmtpRouter.onInitSegment. */
1806
+ onInitSegment(cb: (data: Uint8Array) => void) {
1807
+ this.#router.onInitSegment(cb);
1808
+ }
1809
+ onTrackInit(packetId: number, cb: (data: Uint8Array) => void) {
1810
+ this.#router.onTrackInit(packetId, cb);
1811
+ }
1812
+ onFecBlockStarted(cb: (sbn: number, packetId: number) => void) {
1813
+ this.#router.onFecBlockStarted(cb);
1814
+ }
1815
+ /** Unrecoverable-FEC-block signal. Players drive decoder recovery from this
1816
+ * (a starved decoder cannot resync on its own once the block is abandoned). */
1817
+ onFecBlockFailed(
1818
+ cb: (sbn: number, packetId: number, catalogTrackName?: string) => void,
1819
+ ) {
1820
+ this.#router.onFecBlockFailed(cb);
1821
+ }
1822
+
1823
+ // ---------------------------------------------------------------------------
1824
+ // MSE integration (delegates to MmtpRouter)
1825
+ // ---------------------------------------------------------------------------
1826
+
1827
+ enableMseAssembler(
1828
+ packetId: number,
1829
+ config: Omit<BlockAssemblerConfig, "k">,
1830
+ catalogTrackName?: string,
1831
+ ) {
1832
+ return this.#router.enableMseAssembler(packetId, config, catalogTrackName);
1833
+ }
1834
+
1835
+ onMseSegment(packetId: number, cb: (segment: Uint8Array) => void, catalogTrackName?: string) {
1836
+ this.#router.onMseSegment(packetId, cb, catalogTrackName);
1837
+ }
1838
+
1839
+ onMseSample(packetId: number, cb: (sample: CmafBlockSample) => void, catalogTrackName?: string) {
1840
+ this.#router.onMseSample(packetId, cb, catalogTrackName);
1841
+ }
1842
+
1843
+ onMseInitSegment(packetId: number, cb: (init: Uint8Array) => void, catalogTrackName?: string) {
1844
+ this.#router.onMseInitSegment(packetId, cb, catalogTrackName);
1845
+ }
1846
+
1847
+ emitMseInit(packetId: number, catalogTrackName?: string) {
1848
+ this.#router.emitMseInit(packetId, catalogTrackName);
1849
+ }
1850
+
1851
+ markExternalVideoSync(packetId?: number, catalogTrackName?: string) {
1852
+ this.#router.markExternalVideoSync(packetId, catalogTrackName);
1853
+ }
1854
+
1855
+ // ---------------------------------------------------------------------------
1856
+ // Transport (delegates to MulticastTransport)
1857
+ // ---------------------------------------------------------------------------
1858
+
1859
+ onTakeover(cb: () => void) {
1860
+ this.#transport.onTakeover(cb);
1861
+ }
1862
+ onFailback(cb: (reason: MulticastFailbackReason) => void) {
1863
+ this.#transport.onFailback(cb);
1864
+ }
1865
+ /** See MulticastTransport.onDataPlaneLive: the join's first accepted packet. */
1866
+ onDataPlaneLive(cb: () => void) {
1867
+ this.#transport.onDataPlaneLive(cb);
1868
+ }
1869
+ confirmVideo() {
1870
+ this.#transport.confirmVideo();
1871
+ }
1872
+ confirmAudio() {
1873
+ this.#transport.confirmAudio();
1874
+ }
1875
+
1876
+ static isAvailable(): boolean {
1877
+ return MulticastTransport.isAvailable();
1878
+ }
1879
+
1880
+ async join(config: MulticastEndpointConfig): Promise<boolean> {
1881
+ // A join replaces the admission a staged switch was built on. The new
1882
+ // join's config decides what is admitted, so nothing is restored or
1883
+ // retired here: the switch just ends.
1884
+ const staged = this.#renditionSwitch;
1885
+ if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
1886
+
1887
+ // Configure every FEC/MFU deadline before subscribing so direct-feed and
1888
+ // transport-owned consumers use the same catalog-derived delivery window.
1889
+ this.configureFec(config);
1890
+
1891
+ // Every transport join starts at an arbitrary multicast symbol. Reset only
1892
+ // join-boundary classification; retain configured tracks, decoders, and
1893
+ // cumulative diagnostics across failback/rejoin cycles.
1894
+ this.#fec.beginMulticastJoin();
1895
+ const selectedPacketIds = config.packetIds?.length
1896
+ ? new Set(config.packetIds)
1897
+ : null;
1898
+ const catalogTracks = config.tracks?.filter(({ packetId }) =>
1899
+ selectedPacketIds === null || selectedPacketIds.has(packetId));
1900
+ const ingressTracks = catalogTracks
1901
+ ? catalogTracks
1902
+ : selectedPacketIds === null
1903
+ ? undefined
1904
+ : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
1905
+ const ingress = ingressTracks === undefined
1906
+ ? undefined
1907
+ : {
1908
+ tracks: Object.freeze(
1909
+ ingressTracks.map(({ name, packetId }) =>
1910
+ Object.freeze({ name, packetId }),
1911
+ ),
1912
+ ),
1913
+ };
1914
+ // Precedence between two sources, not a tolerant alias. BOTH operands can
1915
+ // carry a catalog-declared relay, so neither one is "the" inlet:
1916
+ // `amtRelay` — the player/UI override, AND the post-migration catalog
1917
+ // path: `endpointToMulticastConfig` (packages/transport
1918
+ // multicast-catalog-policy.ts) resolves
1919
+ // `multicast.networkSource[{type:"amt"}]` into it
1920
+ // through `findAmtRelay`.
1921
+ // `relayAddress` — the pre-migration per-endpoint relay, retained so a
1922
+ // catalog published before BLO-37834 still joins.
1923
+ // The override/networkSource value wins, else the legacy endpoint value.
1924
+ // `??`, not `||`, so precedence is deliberately NOT trim-aware: a player
1925
+ // clearing its override field means "no AMT", not "fall back to the legacy
1926
+ // relay". Blank is absent for the port decision below but present here.
1927
+ // Retiring `relayAddress` is the legacy cut (BLO-38068), not this branch.
1928
+ const amtRelay = config.amtRelay ?? config.relayAddress;
1929
+ const transportConfig = {
1930
+ sourceAddress: config.sourceAddress,
1931
+ groupAddress: config.groupAddress,
1932
+ port: config.port,
1933
+ mode: config.mode,
1934
+ amtRelay,
1935
+ // A relay here is a commitment to that relay, not a hint: a relay with no
1936
+ // port does NOT fall back to DRIAD, it joins on RFC 7450's 2268.
1937
+ // `toWindowMulticastSubscribeConfig` (packages/transport
1938
+ // endpoint-config.ts) deliberately has no implicit relay port — it throws
1939
+ // and `MulticastTransport.join` resolves false — so the default is
1940
+ // resolved HERE and arrives there explicit, exactly as the two catalog
1941
+ // readers do it. This is the last of the three readers: the `relayAddress`
1942
+ // half cannot supply a port at all (the pre-migration wire shape has no
1943
+ // port field), and `resolveNetworkSource` emits the same port-less shape.
1944
+ // Keyed on the resolved relay, so a DRIAD entry — which pins no relay —
1945
+ // never has a port manufactured for it. Blank counts as no relay, the
1946
+ // same test `catalogAmtNetworkSource` applies (it trims, then skips) and
1947
+ // the same one `toWindowMulticastSubscribeConfig` re-derives downstream
1948
+ // (`input.amtRelay?.trim()`): a port paired with a relay that consumer
1949
+ // reads as absent is a shape no reader here should manufacture. Only the
1950
+ // default is gated — an explicit `amtRelayPort` is caller data and passes
1951
+ // through whatever the relay looks like, since dropping it would be the
1952
+ // worse behaviour.
1953
+ amtRelayPort:
1954
+ config.amtRelayPort ??
1955
+ config.relayPort ??
1956
+ (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : undefined),
1957
+ packetIds: config.packetIds,
1958
+ tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId })),
1959
+ };
1960
+ return ingress === undefined
1961
+ ? this.#transport.join(transportConfig)
1962
+ : this.#transport.join(transportConfig, ingress);
1963
+ }
1964
+
1965
+ // ---------------------------------------------------------------------------
1966
+ // In-place rendition switch
1967
+ // ---------------------------------------------------------------------------
1968
+
1969
+ /**
1970
+ * Switch the live join from one video rendition to another in place: the
1971
+ * subscription (socket, group membership, AMT tunnel) is kept, and the
1972
+ * packet-ID remap commits atomically at a RAP of the incoming rendition.
1973
+ *
1974
+ * Staging widens the admission to carry both renditions: the ingress
1975
+ * tracks become the live ones plus `tracks`, and, when `packetIds` is
1976
+ * given, the allow-list becomes the live one plus `packetIds` (a provider
1977
+ * that cannot widen in place is refused here, before anything changes).
1978
+ * The incoming rendition's packets then feed its FEC and parser while the
1979
+ * outgoing rendition keeps playing, and MmtpRouter.stageStreamSwitch
1980
+ * withholds every incoming frame and its init until the commit.
1981
+ *
1982
+ * The commit is one synchronous step inside the frame path, at the
1983
+ * incoming RAP (see MmtpRouter.stageStreamSwitch for where exactly): the
1984
+ * outgoing packet ID is retired from the router, the admission becomes
1985
+ * exactly `tracks` (and `packetIds`), the outgoing stream's FEC and repair
1986
+ * state is released (FECManager.releasePacket; repair fetches in flight are
1987
+ * aborted through the track-reset observers), `onCommit` runs, and then the
1988
+ * incoming init and RAP are delivered. No outgoing frame is delivered after
1989
+ * it and no incoming frame before it. No timer is armed: the switch waits
1990
+ * on RAPs and on the outgoing stream's own frames.
1991
+ *
1992
+ * Exactly one of `onCommit` and `onCancel` is called per switch. One switch
1993
+ * may be staged at a time.
1994
+ */
1995
+ switchRendition(request: RenditionSwitchRequest): RenditionSwitch {
1996
+ if (this.#renditionSwitch !== null) {
1997
+ throw new Error(
1998
+ "[MulticastManager] a rendition switch is already staged; cancel it before staging another",
1999
+ );
2000
+ }
2001
+ if (typeof request?.onCommit !== "function" || typeof request.onCancel !== "function") {
2002
+ throw new Error("[MulticastManager] switchRendition requires onCommit and onCancel callbacks");
2003
+ }
2004
+ const live = this.#transport.context;
2005
+ if (!this.#transport.joined || live === undefined) {
2006
+ throw new Error(
2007
+ "[MulticastManager] switchRendition needs a live join with catalog ingress tracks: " +
2008
+ "join() with packetIds or tracks first",
2009
+ );
2010
+ }
2011
+ const { from, to } = request;
2012
+ if (!Array.isArray(request.tracks)) {
2013
+ throw new TypeError("[MulticastManager] switchRendition tracks must be an array");
2014
+ }
2015
+ for (const track of request.tracks) {
2016
+ if (
2017
+ typeof track?.name !== "string" ||
2018
+ track.name.length === 0 ||
2019
+ !isMulticastTrackPacketId(track.packetId)
2020
+ ) {
2021
+ throw new RangeError(
2022
+ "[MulticastManager] switchRendition tracks need a non-empty catalog name and a track packet ID each",
2023
+ );
2024
+ }
2025
+ }
2026
+ const holds = (
2027
+ tracks: MmtpIngressContext["tracks"],
2028
+ stream: MmtpStreamIdentity | undefined,
2029
+ ): boolean =>
2030
+ stream !== undefined &&
2031
+ tracks.some((track) => track.name === stream.catalogTrackName && track.packetId === stream.packetId);
2032
+ if (!holds(live.tracks, from)) {
2033
+ throw new Error(
2034
+ `[MulticastManager] switchRendition: from (${from?.catalogTrackName} on ${from?.packetId}) ` +
2035
+ "is not an ingress track of the live join",
2036
+ );
2037
+ }
2038
+ if (to === undefined || live.tracks.some((track) => track.packetId === to.packetId)) {
2039
+ throw new Error(
2040
+ `[MulticastManager] switchRendition: to's packet ID ${to?.packetId} is already admitted ` +
2041
+ "by the live join's ingress; an in-place switch admits a rendition that is not playing",
2042
+ );
2043
+ }
2044
+ if (!holds(request.tracks, to)) {
2045
+ throw new Error("[MulticastManager] switchRendition: tracks must carry to");
2046
+ }
2047
+ if (request.tracks.some((track) => track.packetId === from.packetId)) {
2048
+ throw new Error(
2049
+ `[MulticastManager] switchRendition: tracks must not carry from's packet ID ${from.packetId}; ` +
2050
+ "the commit retires it",
2051
+ );
2052
+ }
2053
+ // While staged, the ingress is the live tracks plus these. One packet ID
2054
+ // under two names is ambiguous to the router, which drops it, so a track
2055
+ // must keep the name the live join gave its packet ID.
2056
+ const renamed = request.tracks.find((track) =>
2057
+ live.tracks.some((liveTrack) => liveTrack.packetId === track.packetId && liveTrack.name !== track.name));
2058
+ if (renamed !== undefined) {
2059
+ throw new Error(
2060
+ `[MulticastManager] switchRendition: tracks name packet ID ${renamed.packetId} ` +
2061
+ `"${renamed.name}", but the live join admits it under another name`,
2062
+ );
2063
+ }
2064
+ const livePacketIds = this.#transport.packetIds;
2065
+ let committedPacketIds: readonly number[] | undefined;
2066
+ if (request.packetIds !== undefined) {
2067
+ if (
2068
+ !Array.isArray(request.packetIds) ||
2069
+ request.packetIds.length === 0 ||
2070
+ !request.packetIds.every(isMulticastTrackPacketId)
2071
+ ) {
2072
+ throw new RangeError(
2073
+ "[MulticastManager] switchRendition packetIds must be a non-empty list of track packet IDs",
2074
+ );
2075
+ }
2076
+ if (!request.packetIds.includes(to.packetId)) {
2077
+ throw new Error("[MulticastManager] switchRendition: packetIds must admit to");
2078
+ }
2079
+ committedPacketIds = Object.freeze([...new Set(request.packetIds)]);
2080
+ } else if (livePacketIds !== null && !livePacketIds.has(to.packetId)) {
2081
+ throw new Error(
2082
+ `[MulticastManager] switchRendition: the live allow-list does not admit to (${to.packetId}); ` +
2083
+ "pass the post-switch packetIds",
2084
+ );
2085
+ }
2086
+
2087
+ const stagedTracks = new Map<string, Readonly<{ name: string; packetId: number }>>();
2088
+ for (const track of [...live.tracks, ...request.tracks]) {
2089
+ stagedTracks.set(`${track.packetId}\0${track.name}`, track);
2090
+ }
2091
+ const stagedIngress = freezeIngress(stagedTracks.values());
2092
+ const stagedPacketIds =
2093
+ committedPacketIds === undefined || livePacketIds === null
2094
+ ? null
2095
+ : new Set([...livePacketIds, ...committedPacketIds]);
2096
+ const widened = stagedPacketIds !== null && !sameIdSet(stagedPacketIds, livePacketIds!);
2097
+
2098
+ const active: ActiveRenditionSwitch = {
2099
+ from: Object.freeze({ packetId: from.packetId, catalogTrackName: from.catalogTrackName }),
2100
+ to: Object.freeze({ packetId: to.packetId, catalogTrackName: to.catalogTrackName }),
2101
+ onCommit: request.onCommit,
2102
+ onCancel: request.onCancel,
2103
+ liveIngress: live,
2104
+ livePacketIds,
2105
+ widened,
2106
+ committedIngress: freezeIngress(request.tracks),
2107
+ committedPacketIds,
2108
+ router: null,
2109
+ state: "staged",
2110
+ };
2111
+ // Throws on an unregistered or non-video stream before any admission changes.
2112
+ active.router = this.#router.stageStreamSwitch({
2113
+ from: active.from,
2114
+ to: active.to,
2115
+ onCommit: (commit) => this.#commitRenditionSwitch(active, commit),
2116
+ });
2117
+ let widening: Promise<void> | undefined;
2118
+ try {
2119
+ if (widened) widening = this.#transport.setPacketIds([...stagedPacketIds!]);
2120
+ this.#transport.setContext(stagedIngress);
2121
+ } catch (error) {
2122
+ active.router.cancel();
2123
+ throw error;
2124
+ }
2125
+ this.#renditionSwitch = active;
2126
+ widening?.catch((error: unknown) => {
2127
+ if (this.#renditionSwitch !== active) return;
2128
+ this.#endRenditionSwitch(active, { reason: "provider-refused", error }, true);
2129
+ });
2130
+ return {
2131
+ get state() {
2132
+ return active.state;
2133
+ },
2134
+ cancel: () => {
2135
+ if (this.#renditionSwitch !== active) return false;
2136
+ this.#endRenditionSwitch(active, { reason: "cancelled" }, true);
2137
+ return true;
2138
+ },
2139
+ };
2140
+ }
2141
+
2142
+ /** The router committed the staged switch (it already retired `from`). */
2143
+ #commitRenditionSwitch(active: ActiveRenditionSwitch, commit: StreamSwitchCommit): void {
2144
+ if (this.#renditionSwitch !== active) return;
2145
+ this.#renditionSwitch = null;
2146
+ active.state = "committed";
2147
+ active.router = null;
2148
+ if (this.#transport.joined) {
2149
+ this.#transport.setContext(active.committedIngress);
2150
+ if (active.committedPacketIds !== undefined) {
2151
+ // The page-side filter narrows now; the provider may keep delivering
2152
+ // the retired IDs until it applies the narrower list, and the page
2153
+ // drops them meanwhile.
2154
+ this.#transport.setPacketIds(active.committedPacketIds).catch((error: unknown) => {
2155
+ console.warn(
2156
+ "[MulticastManager] the provider did not narrow its packet filter after a rendition switch; " +
2157
+ "the page-side filter drops the retired packet IDs",
2158
+ error,
2159
+ );
2160
+ });
2161
+ }
2162
+ }
2163
+ this.#releaseRetiredStream(commit.from);
2164
+ try {
2165
+ active.onCommit(commit);
2166
+ } catch (error) {
2167
+ // The caller could not take `to`. Report it, release what the manager
2168
+ // holds for `to`, and rethrow so the router retires `to` instead of
2169
+ // feeding it to a decoder still configured for `from`.
2170
+ active.state = "failed";
2171
+ this.#releaseRetiredStream(active.to);
2172
+ try {
2173
+ active.onCancel({ reason: "commit-failed", error });
2174
+ } catch (cancelError) {
2175
+ console.warn("[MulticastManager] rendition switch onCancel failed", cancelError);
2176
+ }
2177
+ throw error;
2178
+ }
2179
+ }
2180
+
2181
+ /**
2182
+ * End a staged switch without committing. `restore` puts the pre-switch
2183
+ * admission back and retires `to`; a join or dispose supersedes both.
2184
+ */
2185
+ #endRenditionSwitch(
2186
+ active: ActiveRenditionSwitch,
2187
+ cancel: RenditionSwitchCancel,
2188
+ restore: boolean,
2189
+ ): void {
2190
+ if (this.#renditionSwitch !== active) return;
2191
+ this.#renditionSwitch = null;
2192
+ active.state = "cancelled";
2193
+ active.router?.cancel();
2194
+ active.router = null;
2195
+ if (restore) {
2196
+ if (this.#transport.joined) {
2197
+ this.#transport.setContext(active.liveIngress);
2198
+ if (active.widened && active.livePacketIds !== null) {
2199
+ this.#transport.setPacketIds([...active.livePacketIds]).catch((error: unknown) => {
2200
+ console.warn(
2201
+ "[MulticastManager] the provider did not narrow its packet filter after a cancelled " +
2202
+ "rendition switch; the page-side filter drops the incoming packet IDs",
2203
+ error,
2204
+ );
2205
+ });
2206
+ }
2207
+ }
2208
+ this.#router.retirePacketId(active.to.packetId);
2209
+ this.#releaseRetiredStream(active.to);
2210
+ }
2211
+ try {
2212
+ active.onCancel(cancel);
2213
+ } catch (error) {
2214
+ console.warn("[MulticastManager] rendition switch onCancel failed", error);
2215
+ }
2216
+ }
2217
+
2218
+ /**
2219
+ * Release what the manager and FEC hold for a stream whose packet ID the
2220
+ * router retired, or whose FEC a catalog reconfiguration no longer configures.
2221
+ */
2222
+ #releaseRetiredStream(stream: MmtpStreamIdentity): void {
2223
+ // Repair transports abort I/O for a stream on a reset notice
2224
+ // (wireRepairFetch); a retired stream's repair fetches end with it.
2225
+ for (const observer of this.#trackResetObservers) {
2226
+ try {
2227
+ observer(stream.packetId, stream.catalogTrackName);
2228
+ } catch (error) {
2229
+ console.warn("[MulticastManager] track reset observer failed", error);
2230
+ }
2231
+ }
2232
+ for (const key of [...this.#repairInFlight]) {
2233
+ try {
2234
+ const [keyPacketId] = JSON.parse(key);
2235
+ if (keyPacketId === stream.packetId) this.#repairInFlight.delete(key);
2236
+ } catch {
2237
+ // Internal keys are JSON tuples; preserve unknown legacy entries.
2238
+ }
2239
+ }
2240
+ for (const [key, stats] of [...this.#blockPolicyStats]) {
2241
+ if (stats.packetId === stream.packetId) this.#blockPolicyStats.delete(key);
2242
+ }
2243
+ // The retired track stops contributing to the stream-global FEC timing;
2244
+ // the deadlines already applied stay until the next configuration
2245
+ // re-reduces them, which only ever errs toward the wider window.
2246
+ this.#trackFecTiming.delete(stream.packetId);
2247
+ this.#multiTrackFecTracks.delete(stream.packetId);
2248
+ this.#fec.releasePacket(stream.packetId);
2249
+ }
2250
+
2251
+ /** Feed a raw packet from an external source (AMT tunnel, ASM subscription).
2252
+ *
2253
+ * For MoQ-unicast-fallback mode (no SSM bridge), call
2254
+ * `manager.router.feedPacket(packet, "moq")` directly to bypass
2255
+ * MulticastTransport's takeover/watchdog/failback gates while preserving
2256
+ * transport attribution in FEC path counters.
2257
+ * The `router` accessor above is already public.
2258
+ */
2259
+ feedPacket(data: ArrayBuffer | Uint8Array, ingress?: MmtpIngressContext) {
2260
+ this.#transport.feedPacket(data, ingress);
2261
+ }
2262
+
2263
+ /**
2264
+ * Declare how packets given to feedPacket() reach this manager. A consumer
2265
+ * that owns the multicast socket itself declares its own leg; join()
2266
+ * applies what the window.multicast subscription declares instead.
2267
+ */
2268
+ setMulticastSymbolDelivery(delivery: MulticastSymbolDelivery): void {
2269
+ this.#fec.setMulticastSymbolDelivery(delivery);
2270
+ }
2271
+
2272
+ /** Process a repair packet from MoQ (reliable QUIC). */
2273
+ processRepairFromMoQ(
2274
+ packet: Uint8Array,
2275
+ ownerPacketId?: number,
2276
+ catalogTrackName?: string,
2277
+ ) {
2278
+ this.#router.feedRepairPacket(packet, ownerPacketId, catalogTrackName);
2279
+ }
2280
+
2281
+ /** Route a Worker-recovered FEC block through the MMTP parser + dedup pipeline. */
2282
+ routeRecoveredBlock(
2283
+ blockId: number,
2284
+ data: Uint8Array,
2285
+ packetId: number,
2286
+ catalogTrackName?: string,
2287
+ ) {
2288
+ this.#router.routeRecoveredBlock(blockId, data, packetId, catalogTrackName);
2289
+ }
2290
+
2291
+ /** Route one Worker-recovered source symbol through the MMTP parser + dedup pipeline. */
2292
+ routeRecoveredSymbol(
2293
+ blockId: number,
2294
+ data: Uint8Array,
2295
+ packetId: number,
2296
+ esi = 0,
2297
+ catalogTrackName?: string,
2298
+ ) {
2299
+ this.#router.routeRecoveredSymbol(blockId, data, packetId, esi, catalogTrackName);
2300
+ }
2301
+
2302
+ // ---------------------------------------------------------------------------
2303
+ // Phase 14: multi-track catalog ingest (D-04, D-06, D-07, D-17, D-26, D-28)
2304
+ // ---------------------------------------------------------------------------
2305
+
2306
+ /**
2307
+ * Configure the manager for a multi-track (base/delta/repair) CMAF switching set.
2308
+ *
2309
+ * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
2310
+ * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
2311
+ * D-17: Builds altGroup → track-name index for getSwitchingSet().
2312
+ * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
2313
+ *
2314
+ * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
2315
+ * whose `fec` names no implemented `blockProfile` (only `iso-ssbg1-v1` is
2316
+ * implemented; the retired `k-padded-v1` is not), or an `iso-ssbg1-v1` span
2317
+ * it cannot use, is consumed without FEC: it gets no decoder, and none of
2318
+ * its repair tracks (layer 0 by `fec.repairTrack`, further layers and the
2319
+ * overlay by `depends`) is given an owner, so the router drops their packets
2320
+ * before any decoder. Those legs keep the `repair` role and their owner's
2321
+ * switching set. Neither the call nor any other track's FEC fails on that
2322
+ * account; `trackFecUnavailable(name)` reports the reason. FEC a previous
2323
+ * call configured on a packetId this call does not is released
2324
+ * (FECManager.releasePacket); frames its release gate held are delivered in
2325
+ * order, each gap stalled. FEC wired by hand (setFecDecoder) is left alone.
2326
+ * Geometry a decoder could not configure (K, P, T, `repairTrack`,
2327
+ * algorithm) still throws.
2328
+ *
2329
+ * @param catalog - Multi-track catalog (tracks array with name, altGroup, fec, packetId).
2330
+ * @param wasmDecoderSource - One WASM FEC decoder for a single FEC stream, or
2331
+ * a factory returning a distinct decoder per stream.
2332
+ */
2333
+ configureMultiTrack(
2334
+ catalog: MultiTrackCatalog,
2335
+ wasmDecoderSource?: WasmFecDecoder | WasmFecDecoderFactory,
2336
+ ): void {
2337
+ // D-06: Resolve explicit fec.repairTrack pointers FIRST. This allows
2338
+ // publisher-chosen repair track names (e.g. "video/repair-alt") that don't
2339
+ // match the standard "/repair" suffix convention. The explicit pointer wins
2340
+ // over the naming convention: a track pointed to by repairTrack is always
2341
+ // 'repair'. The pointer lives on the owner, and a repair leg is a raw
2342
+ // application/raptorq track the publisher never tags with an altGroup, so
2343
+ // the leg belongs to its owner's group regardless of what the leg itself
2344
+ // declares.
2345
+ //
2346
+ // Layers 1..n and a keyframe overlay are named only by their own `depends`
2347
+ // (draft-ramadan-moq-fec §6.3), so they are resolved here too. A layer that
2348
+ // did not reach this map would fall through to parseTrackRole and be
2349
+ // mis-roled or rejected on its name, and would land in its own altGroup
2350
+ // rather than its owner's.
2351
+ const repairNamesBySource = repairTrackNamesBySource(catalog.tracks);
2352
+ // §5.1: classify each media track's FEC before roles are resolved. A track
2353
+ // whose FEC is unavailable still names its layer 0 by `fec.repairTrack`;
2354
+ // that pointer is a catalog fact about the leg, not about the profile, so
2355
+ // the leg stays roled `repair` in its owner's group rather than falling
2356
+ // through to its name. It is never given an owner below.
2357
+ const declaredRepairNames = new Set<string>();
2358
+ for (const names of repairNamesBySource.values()) {
2359
+ for (const name of names) declaredRepairNames.add(name);
2360
+ }
2361
+ const fecUnavailableByTrack = new Map<string, TrackFecUnavailable>();
2362
+ for (let i = 0; i < catalog.tracks.length; i++) {
2363
+ const track = catalog.tracks[i]!;
2364
+ if (
2365
+ track.fec === undefined ||
2366
+ track.packaging === "fec-repair" ||
2367
+ declaredRepairNames.has(track.name)
2368
+ ) {
2369
+ continue;
2370
+ }
2371
+ const fecUnavailable = catalogFecUnavailable(track.fec, `$.tracks[${i}].fec`);
2372
+ if (fecUnavailable === undefined) continue;
2373
+ fecUnavailableByTrack.set(track.name, fecUnavailable);
2374
+ const layerZero = (track.fec as { repairTrack?: unknown }).repairTrack;
2375
+ if (typeof layerZero === "string" && layerZero.length > 0) {
2376
+ const names = repairNamesBySource.get(track.name) ?? new Set<string>();
2377
+ names.add(layerZero);
2378
+ repairNamesBySource.set(track.name, names);
2379
+ }
2380
+ }
2381
+ // Every repair leg of a source without FEC goes unowned, including one a
2382
+ // source with FEC also names: the router could not tell the two sources'
2383
+ // symbols apart on it, and the unavailable source's must reach no decoder.
2384
+ const unownedRepairNames = new Set<string>();
2385
+ for (const sourceName of fecUnavailableByTrack.keys()) {
2386
+ for (const repairName of repairNamesBySource.get(sourceName) ?? []) {
2387
+ unownedRepairNames.add(repairName);
2388
+ }
2389
+ }
2390
+ const repairOwnerGroup = new Map<string, string>();
2391
+ const repairOwnerAltGroup = new Map<string, number | undefined>();
2392
+ for (const track of catalog.tracks) {
2393
+ for (const repairName of repairNamesBySource.get(track.name) ?? []) {
2394
+ repairOwnerGroup.set(repairName, altGroupKey(track));
2395
+ repairOwnerAltGroup.set(repairName, track.altGroup);
2396
+ }
2397
+ }
2398
+ const groupKeyFor = (track: MultiTrackCatalogTrack): string =>
2399
+ repairOwnerGroup.get(track.name) ?? altGroupKey(track);
2400
+
2401
+ const trackNamesByGroup = new Map<string, string[]>();
2402
+ for (const track of catalog.tracks) {
2403
+ const groupKey = groupKeyFor(track);
2404
+ const groupNames = trackNamesByGroup.get(groupKey) ?? [];
2405
+ groupNames.push(track.name);
2406
+ trackNamesByGroup.set(groupKey, groupNames);
2407
+ }
2408
+
2409
+ const hasSwitchingSetByGroup = new Map<string, boolean>();
2410
+ for (const [groupKey, trackNames] of trackNamesByGroup) {
2411
+ hasSwitchingSetByGroup.set(groupKey, hasSwitchingSetRole(trackNames));
2412
+ }
2413
+
2414
+ // Resolve role for each track — explicit pointer wins over naming convention.
2415
+ // Normalize non-standard repair names to 'repair' before calling validateSwitchingSet,
2416
+ // which relies on parseTrackRole and would throw on custom repair-track names.
2417
+ const resolvedRoles: TrackRole[] = catalog.tracks.map((track) => {
2418
+ if (repairOwnerGroup.has(track.name)) return "repair";
2419
+ const hasSwitchingSet = hasSwitchingSetByGroup.get(altGroupKey(track)) ?? false;
2420
+ if (!hasSwitchingSet) return "single";
2421
+ return parseTrackRole(track.name);
2422
+ });
2423
+
2424
+ // D-04: Validate completeness per altGroup using resolved roles.
2425
+ // We replicate validateSwitchingSet logic here to avoid re-calling parseTrackRole
2426
+ // (which would throw on explicit-pointer repair track names like "video/repair-alt").
2427
+ const resolvedRolesByGroup = new Map<string, TrackRole[]>();
2428
+ for (let i = 0; i < catalog.tracks.length; i++) {
2429
+ const groupKey = groupKeyFor(catalog.tracks[i]!);
2430
+ const roles = resolvedRolesByGroup.get(groupKey) ?? [];
2431
+ roles.push(resolvedRoles[i]!);
2432
+ resolvedRolesByGroup.set(groupKey, roles);
2433
+ }
2434
+ for (const [groupKey, roles] of resolvedRolesByGroup) {
2435
+ if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
2436
+
2437
+ const presentRoles = new Set(roles.filter((r) => r !== "single"));
2438
+ const required: Array<"base" | "delta" | "repair"> = [
2439
+ "base",
2440
+ "delta",
2441
+ "repair",
2442
+ ];
2443
+ const missing = required.filter((r) => !presentRoles.has(r));
2444
+ if (missing.length > 0) {
2445
+ throw new Error(
2446
+ `[MulticastManager] incomplete switching set: missing ${missing.join(", ")}`,
2447
+ );
2448
+ }
2449
+ }
2450
+
2451
+ const fecTrackIndexes: number[] = [];
2452
+ for (let i = 0; i < catalog.tracks.length; i++) {
2453
+ const track = catalog.tracks[i]!;
2454
+ if (resolvedRoles[i] === "repair" || track.fec === undefined) continue;
2455
+ // Malformed geometry fails the call whatever the profile says; an
2456
+ // unavailable profile or span only costs this track its FEC (§5.1).
2457
+ const unavailable = fecUnavailableByTrack.has(track.name);
2458
+ if (!(unavailable ? isFecCatalogGeometry(track.fec) : isFecCatalogConfig(track.fec))) {
2459
+ throw new Error(
2460
+ `[MulticastManager] invalid fec config for track '${track.name}'`,
2461
+ );
2462
+ }
2463
+ if (unavailable) continue;
2464
+ if (track.packetId !== undefined) fecTrackIndexes.push(i);
2465
+ }
2466
+
2467
+ // Stateful decoders cannot span physical streams: resetting one stream
2468
+ // would otherwise clear or disable every peer sharing that instance.
2469
+ const fecDecoders = new Map<number, WasmFecDecoder>();
2470
+ if (wasmDecoderSource !== undefined && fecTrackIndexes.length > 0) {
2471
+ if (typeof wasmDecoderSource !== "function") {
2472
+ if (fecTrackIndexes.length > 1) {
2473
+ throw new Error(
2474
+ "[MulticastManager] multiple FEC streams require a decoder factory",
2475
+ );
2476
+ }
2477
+ fecDecoders.set(fecTrackIndexes[0]!, wasmDecoderSource);
2478
+ } else {
2479
+ const clients = new Set<WasmFecDecoder>();
2480
+ for (const index of fecTrackIndexes) {
2481
+ const client = wasmDecoderSource(catalog.tracks[index]!);
2482
+ if (clients.has(client)) {
2483
+ throw new Error(
2484
+ "[MulticastManager] decoder factory must return one client per physical stream",
2485
+ );
2486
+ }
2487
+ clients.add(client);
2488
+ fecDecoders.set(index, client);
2489
+ }
2490
+ }
2491
+ }
2492
+
2493
+ // Reset switching-set index, repair packetId set and FEC availability.
2494
+ this.#switchingSets.clear();
2495
+ this.#repairPacketIds.clear();
2496
+ this.#router.clearRepairPacketIdOwners();
2497
+ // FEC a previous call configured that this one does not (the source is
2498
+ // gone, lost its `fec`, or its FEC is now unavailable) must not stay
2499
+ // installed: its symbols would still be read as block coordinates and
2500
+ // held for repair legs that no longer have an owner. FEC a caller wired
2501
+ // by hand is not this call's to release.
2502
+ const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i]!.packetId));
2503
+ // The record survives a throw below: a packet this call configures again
2504
+ // is overwritten by its set(), and a released one is dropped by
2505
+ // #releaseRetiredStream.
2506
+ for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
2507
+ if (fecPacketIds.has(packetId)) continue;
2508
+ if (!this.#fec.isTrackConfigured(packetId)) {
2509
+ this.#multiTrackFecTracks.delete(packetId);
2510
+ continue;
2511
+ }
2512
+ this.#router.releaseFecPacket(packetId);
2513
+ this.#releaseRetiredStream({ packetId, catalogTrackName });
2514
+ }
2515
+ this.#fecUnavailableByTrack.clear();
2516
+ for (const [name, reason] of fecUnavailableByTrack) {
2517
+ this.#fecUnavailableByTrack.set(name, reason);
2518
+ }
2519
+ const catalogTracksByName = new Map(
2520
+ catalog.tracks.map((track) => [track.name, track] as const),
2521
+ );
2522
+
2523
+ for (let i = 0; i < catalog.tracks.length; i++) {
2524
+ const track = catalog.tracks[i]!;
2525
+ const role = resolvedRoles[i]!;
2526
+
2527
+ // D-17: Build altGroup → track-name index. A repair leg belongs to the
2528
+ // switching set of the owner that points at it.
2529
+ const altGroup = repairOwnerAltGroup.has(track.name)
2530
+ ? repairOwnerAltGroup.get(track.name)
2531
+ : track.altGroup;
2532
+ if (altGroup !== undefined) {
2533
+ const existing = this.#switchingSets.get(altGroup) ?? [];
2534
+ existing.push(track.name);
2535
+ this.#switchingSets.set(altGroup, existing);
2536
+ }
2537
+
2538
+ // D-26: Register packetId → role on MmtpRouter (if packetId provided at ingest time).
2539
+ if (track.packetId !== undefined) {
2540
+ this.#router.setPacketIdRole(track.packetId, role);
2541
+ }
2542
+
2543
+ if (role === "repair") {
2544
+ // D-06: Repair track is the repair source — no FEC decoder registered on it.
2545
+ if (track.packetId !== undefined) {
2546
+ this.#repairPacketIds.add(track.packetId);
2547
+ }
2548
+ continue;
2549
+ }
2550
+
2551
+ // D-07: Apply per-track FEC config for non-repair tracks. A track whose
2552
+ // FEC is unavailable (§5.1) is consumed like a track without `fec`.
2553
+ if (track.fec !== undefined && !fecUnavailableByTrack.has(track.name)) {
2554
+ const fecCfg = track.fec as FecCatalogConfig;
2555
+ // Every repair layer and the keyframe overlay route to this source's
2556
+ // decoder, not only layer 0. A layer whose packetId had no registered
2557
+ // owner would have its repair symbols dropped as an unknown owner, and
2558
+ // two sources whose RS_ID ranges overlap would be indistinguishable.
2559
+ if (track.packetId !== undefined) {
2560
+ for (const repairName of repairNamesBySource.get(track.name) ?? []) {
2561
+ if (unownedRepairNames.has(repairName)) continue;
2562
+ const repairTrack = catalogTracksByName.get(repairName);
2563
+ if (repairTrack?.packetId !== undefined) {
2564
+ this.#router.setRepairPacketIdOwner(repairTrack.packetId, track.packetId);
2565
+ }
2566
+ }
2567
+ }
2568
+ const wasmDecoder = fecDecoders.get(i);
2569
+ if (track.packetId !== undefined && wasmDecoder !== undefined) {
2570
+ // trackType: base/delta/single video tracks are 'video'; audio would be 'audio'.
2571
+ // At this layer we treat all content tracks as 'video' — audio tracks typically
2572
+ // have no FEC in Phase 14 (D-26 covers video base+delta only). Callers that need
2573
+ // audio FEC can call setFecDecoder() directly after configureMultiTrack().
2574
+ const blockProfile = parseFecBlockProfile(
2575
+ (fecCfg as { blockProfile?: unknown }).blockProfile,
2576
+ `tracks[${JSON.stringify(track.name)}].fec.blockProfile`,
2577
+ );
2578
+ this.#fec.setFecDecoder(
2579
+ track.packetId,
2580
+ wasmDecoder,
2581
+ fecCfg.sourceSymbols,
2582
+ {
2583
+ blockProfile,
2584
+ k: fecCfg.sourceSymbols,
2585
+ symbolSize: fecCfg.symbolSize,
2586
+ interleaveDepthMs: fecCfg.interleaveDepthMs,
2587
+ fps: track.framerate,
2588
+ trackKind: "video",
2589
+ },
2590
+ track.name,
2591
+ );
2592
+ this.#multiTrackFecTracks.set(track.packetId, track.name);
2593
+ this.#configureTrackMapper(track.packetId, {
2594
+ blockProfile,
2595
+ k: fecCfg.sourceSymbols,
2596
+ symbolSize: fecCfg.symbolSize,
2597
+ interleaveDepthMs: fecCfg.interleaveDepthMs,
2598
+ fps: track.framerate,
2599
+ });
2600
+ this.#router.setPacketIdType(track.packetId, "video");
2601
+ }
2602
+ }
2603
+ }
2604
+ }
2605
+
2606
+ /**
2607
+ * Why `configureMultiTrack` consumes the named catalog track without FEC
2608
+ * although its `fec` block declares one (draft-ramadan-moq-fec §5.1): no
2609
+ * implemented `blockProfile` (`track_fec_block_profile_unimplemented`, e.g.
2610
+ * the retired `k-padded-v1`; `track_fec_block_profile` when absent), or an
2611
+ * `iso-ssbg1-v1` span it cannot use (`track_fec_block_span` when absent,
2612
+ * `track_fec` when declared but unusable). The same reason the hang
2613
+ * resolver reports (`catalogFecUnavailable`). Undefined for every other
2614
+ * track, and for every track before the first call; each call replaces the
2615
+ * previous call's answers.
2616
+ */
2617
+ trackFecUnavailable(trackName: string): TrackFecUnavailable | undefined {
2618
+ return this.#fecUnavailableByTrack.get(trackName);
2619
+ }
2620
+
2621
+ /** Per-track FEC availability from the last `configureMultiTrack` call. */
2622
+ readonly #fecUnavailableByTrack = new Map<string, TrackFecUnavailable>();
2623
+
2624
+ /** packetId → catalog track name of the FEC the last `configureMultiTrack` installed. */
2625
+ readonly #multiTrackFecTracks = new Map<number, string>();
2626
+
2627
+ /**
2628
+ * Return the track names belonging to the given altGroup switching set.
2629
+ * D-17: altGroup groups base+delta+repair into one switching set.
2630
+ *
2631
+ * @param altGroup - The altGroup number to look up.
2632
+ * @returns Array of track names in that switching set (empty if none).
2633
+ */
2634
+ getSwitchingSet(altGroup: number): string[] {
2635
+ return this.#switchingSets.get(altGroup) ?? [];
2636
+ }
2637
+
2638
+ /**
2639
+ * Register callback fired when a repair fetch should be issued for an FEC block.
2640
+ *
2641
+ * D-28: At most one outstanding repair fetch per (packetId, sbn) block.
2642
+ * clearRepairForBlock fires automatically when the block resolves (via
2643
+ * FECManager.onRepairResolved); call it manually only on fetch failure
2644
+ * paths the FEC layer cannot observe (fetch error, range not retained,
2645
+ * transport timeout) so a stuck fetch cannot wedge the block's slot.
2646
+ *
2647
+ * Registering also arms the FEC repair deadline: each block gets a one-shot
2648
+ * timer for the derived K-symbol source-production horizon; a block still
2649
+ * short of K when it fires requests repair here. Failure accounting timing
2650
+ * is unchanged.
2651
+ */
2652
+ onRepairSubscribe(cb: RepairSubscribeCallback): void {
2653
+ this.#onRepairSubscribeCb = cb;
2654
+ this.#fec.onRepairNeeded = (sbn, packetId, catalogTrackName, blockClass) => {
2655
+ this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
2656
+ };
2657
+ }
2658
+
2659
+ /**
2660
+ * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
2661
+ * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
2662
+ * not sent. Emits one `repair-priority` lifecycle event.
2663
+ */
2664
+ noteRepairPriority(
2665
+ action: "omitted" | "declined",
2666
+ reason: RepairPriorityReason,
2667
+ blockClass: BlockClass,
2668
+ sbn: number,
2669
+ packetId: number,
2670
+ catalogTrackName?: string,
2671
+ ): void {
2672
+ this.#emitRepairLifecycle({
2673
+ version: 2,
2674
+ type: "repair-priority",
2675
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
2676
+ blockClass,
2677
+ action,
2678
+ reason,
2679
+ });
2680
+ }
2681
+
2682
+ /** Record a repair request the scheduler sent no FETCH for. */
2683
+ noteRepairSkipped(
2684
+ reason: RepairSkipReason,
2685
+ measurement: { readonly rttMs: number | null; readonly budgetMs: number },
2686
+ sbn: number,
2687
+ packetId: number,
2688
+ catalogTrackName?: string,
2689
+ ): void {
2690
+ this.#statsFor(packetId, catalogTrackName).repairsSkipped++;
2691
+ this.#emitRepairLifecycle({
2692
+ version: 2,
2693
+ type: "repair-skipped",
2694
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
2695
+ reason,
2696
+ rttMs: measurement.rttMs,
2697
+ budgetMs: measurement.budgetMs,
2698
+ });
2699
+ }
2700
+
2701
+ /**
2702
+ * Record a repair-scheduler decision about a delta block: preempted for
2703
+ * keyframe/audio work, or never dispatched before its block resolved.
2704
+ */
2705
+ noteRepairScheduling(
2706
+ type: "repair-preempted" | "repair-deferred",
2707
+ sbn: number,
2708
+ packetId: number,
2709
+ catalogTrackName?: string,
2710
+ ): void {
2711
+ const stats = this.#statsFor(packetId, catalogTrackName);
2712
+ if (type === "repair-preempted") stats.deltaRepairsPreempted++;
2713
+ else stats.deltaRepairsDeferred++;
2714
+ this.#emitRepairLifecycle({
2715
+ version: 2,
2716
+ type,
2717
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
2718
+ });
2719
+ }
2720
+
2721
+ /** Catalog/reset epoch of a packet's streams; gap decisions carry it. */
2722
+ epochFor(packetId: number): number {
2723
+ return this.#fec.epochFor(packetId);
2724
+ }
2725
+
2726
+ /**
2727
+ * Keyframe-protected repair policy counters, keyed by catalog track name
2728
+ * (`packetId:<n>` for a stream with no catalog name). Each track's
2729
+ * counters reset with its epoch.
2730
+ */
2731
+ getBlockPolicyStats(): Record<string, BlockPolicyStats> {
2732
+ const out: Record<string, BlockPolicyStats> = {};
2733
+ for (const [key, stats] of this.#blockPolicyStats) {
2734
+ if (stats.epoch !== this.#fec.epochFor(stats.packetId)) continue;
2735
+ out[key] = { ...stats };
2736
+ }
2737
+ return out;
2738
+ }
2739
+
2740
+ #statsFor(packetId: number, catalogTrackName?: string): BlockPolicyStats {
2741
+ const key = catalogTrackName ?? `packetId:${packetId}`;
2742
+ const epoch = this.#fec.epochFor(packetId);
2743
+ let stats = this.#blockPolicyStats.get(key);
2744
+ if (!stats || stats.epoch !== epoch || stats.packetId !== packetId) {
2745
+ stats = newBlockPolicyStats(packetId, catalogTrackName ?? null, epoch);
2746
+ this.#blockPolicyStats.set(key, stats);
2747
+ }
2748
+ return stats;
2749
+ }
2750
+
2751
+ /**
2752
+ * Observe causal repair lifecycle events without retaining snapshots in the
2753
+ * transport. Returns an unsubscribe function.
2754
+ */
2755
+ addRepairLifecycleObserver(observer: RepairLifecycleObserver): () => void {
2756
+ this.#repairLifecycleObservers.add(observer);
2757
+ return () => this.#repairLifecycleObservers.delete(observer);
2758
+ }
2759
+
2760
+ /** Observe per-stream epoch resets (used by repair transports to abort I/O). */
2761
+ addTrackResetObserver(
2762
+ observer: (packetId: number, catalogTrackName: string) => void,
2763
+ ): () => void {
2764
+ this.#trackResetObservers.add(observer);
2765
+ return () => this.#trackResetObservers.delete(observer);
2766
+ }
2767
+
2768
+ /** Begin a fresh retained-replay epoch for one physical media stream. */
2769
+ resetTrack(packetId: number, catalogTrackName: string): void {
2770
+ if (!catalogTrackName) {
2771
+ throw new Error('[MulticastManager] catalogTrackName is required for track reset');
2772
+ }
2773
+ this.#resetStreamOutsideRouter(packetId, catalogTrackName);
2774
+ this.#router.resetTrack(packetId, catalogTrackName);
2775
+ }
2776
+
2777
+ /** resetTrack() for everything but the router's own state. */
2778
+ #resetStreamOutsideRouter(packetId: number, catalogTrackName: string): void {
2779
+ for (const observer of this.#trackResetObservers) {
2780
+ try {
2781
+ observer(packetId, catalogTrackName);
2782
+ } catch (error) {
2783
+ console.warn('[MulticastManager] track reset observer failed', error);
2784
+ }
2785
+ }
2786
+ for (const key of this.#repairInFlight) {
2787
+ try {
2788
+ const [keyPacketId, keyTrackName] = JSON.parse(key);
2789
+ if (keyPacketId === packetId && keyTrackName === catalogTrackName) {
2790
+ this.#repairInFlight.delete(key);
2791
+ }
2792
+ } catch {
2793
+ // Internal keys are JSON tuples; preserve unknown legacy entries.
2794
+ }
2795
+ }
2796
+ this.#fec.resetTrack(packetId, catalogTrackName);
2797
+ }
2798
+
2799
+ /**
2800
+ * Request a repair-track fetch for the given FEC block.
2801
+ *
2802
+ * D-28: duplicate requests for the same (packetId, sbn) are suppressed
2803
+ * until clearRepairForBlock is called.
2804
+ *
2805
+ * @param sbn - Source Block Number identifying the FEC block needing repair.
2806
+ * @param packetId - MMTP packet_id owning the block (video/audio tracks have
2807
+ * independent SBN spaces, so the in-flight key must be composite).
2808
+ */
2809
+ requestRepairForBlock(
2810
+ sbn: number,
2811
+ packetId: number,
2812
+ catalogTrackName: string | undefined,
2813
+ blockClass: BlockClass,
2814
+ ): void {
2815
+ // D-28: at most one outstanding fetch per FEC block (per packetId:sbn).
2816
+ // Different blocks are independent and are NOT blocked by each other.
2817
+ const block = repairBlockIdentity(packetId, sbn, catalogTrackName);
2818
+ const key = JSON.stringify([packetId, block.catalogTrackName, sbn]);
2819
+ if (this.#repairInFlight.has(key)) return;
2820
+ this.#repairInFlight.add(key);
2821
+ const stats = this.#statsFor(packetId, catalogTrackName);
2822
+ if (blockClass === "keyframe") stats.keyframeBlocksProtected++;
2823
+ else if (blockClass === "unknown") stats.unknownBlocksProtected++;
2824
+ else if (blockClass === "delta") stats.deltaBlocksShort++;
2825
+ this.#emitRepairLifecycle({
2826
+ version: 2,
2827
+ type: "requested",
2828
+ block,
2829
+ blockClass,
2830
+ priority: repairPriorityForClass(blockClass),
2831
+ });
2832
+ this.#onRepairSubscribeCb?.(sbn, packetId, catalogTrackName, blockClass);
2833
+ }
2834
+
2835
+ /**
2836
+ * Clear in-flight repair state for the given block.
2837
+ * Fired automatically when the block resolves; safe to call redundantly.
2838
+ */
2839
+ clearRepairForBlock(
2840
+ sbn: number,
2841
+ packetId: number,
2842
+ catalogTrackName?: string,
2843
+ ): void {
2844
+ this.#repairInFlight.delete(
2845
+ JSON.stringify([packetId, catalogTrackName ?? null, sbn]),
2846
+ );
2847
+ }
2848
+
2849
+ #emitRepairLifecycle(event: RepairLifecycleEvent): void {
2850
+ // A gap decision is already frozen and is the same object the frame
2851
+ // carries as gapBefore: forward it as is, never a copy.
2852
+ const immutableEvent = event.type === "gap"
2853
+ ? event
2854
+ : (Object.freeze(
2855
+ "stream" in event
2856
+ ? { ...event, stream: Object.freeze({ ...event.stream }) }
2857
+ : {
2858
+ ...event,
2859
+ block: Object.freeze({ ...event.block }),
2860
+ ...("symbols" in event
2861
+ ? { symbols: Object.freeze({ ...event.symbols }) }
2862
+ : {}),
2863
+ },
2864
+ ) as RepairLifecycleEvent);
2865
+ // Serialize before invoking observers so a re-entrant observer cannot log
2866
+ // a resolution before the request that caused it.
2867
+ if (this.#logRepairLifecycle) {
2868
+ console.info(
2869
+ `${REPAIR_LIFECYCLE_LOG_PREFIX}${JSON.stringify(immutableEvent)}`,
2870
+ );
2871
+ }
2872
+ for (const observer of this.#repairLifecycleObservers) {
2873
+ try {
2874
+ observer(immutableEvent);
2875
+ } catch (error) {
2876
+ console.warn("[MulticastManager] repair lifecycle observer failed", error);
2877
+ }
2878
+ }
2879
+ }
2880
+
2881
+ dispose() {
2882
+ const staged = this.#renditionSwitch;
2883
+ if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
2884
+ this.#trackResetObservers.clear();
2885
+ this.#repairLifecycleObservers.clear();
2886
+ this.#transport.dispose();
2887
+ this.#router.dispose();
2888
+ this.#fec.dispose();
2889
+ }
2890
+ }
2891
+
2892
+ // Compile-time contract: the manager is the host the D-28 repair scheduler
2893
+ // (wireRepairFetch) drives.
2894
+ const repairFetchHost = (manager: MulticastManager): RepairFetchHost => manager;
2895
+ void repairFetchHost;