@torrent-tv/proxy 2.89.5 → 2.89.7

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 (447) hide show
  1. package/.claude/commands/opsx/apply.md +155 -155
  2. package/.claude/commands/opsx/archive.md +160 -160
  3. package/.claude/commands/opsx/explore.md +174 -174
  4. package/.claude/commands/opsx/propose.md +109 -109
  5. package/.claude/commands/opsx/sync.md +143 -143
  6. package/.claude/skills/openspec-apply-change/SKILL.md +159 -159
  7. package/.claude/skills/openspec-archive-change/SKILL.md +117 -117
  8. package/.claude/skills/openspec-explore/SKILL.md +289 -289
  9. package/.claude/skills/openspec-propose/SKILL.md +113 -113
  10. package/.claude/skills/openspec-sync-specs/SKILL.md +147 -147
  11. package/.dockerignore +5 -5
  12. package/AGENTS.md +338 -338
  13. package/CHANGELOG.md +16 -0
  14. package/Dockerfile +30 -30
  15. package/LICENSE +16 -16
  16. package/README.md +369 -369
  17. package/assets/calibration/NOTICE.md +100 -100
  18. package/assets/diagnostics/sctpstate.gdb +31 -31
  19. package/bin/cli.js +684 -684
  20. package/bin/thread-pool.js +30 -30
  21. package/docs/download-architecture.md +261 -261
  22. package/docs/encode-architecture.md +765 -765
  23. package/docs/encode-run-state.md +96 -96
  24. package/docs/logs.md +97 -97
  25. package/docs/playback-start-forecast.md +17 -2
  26. package/docs/socks5-egress-research.md +114 -114
  27. package/docs/storage-architecture.md +273 -273
  28. package/knip.json +14 -14
  29. package/openspec/changes/adaptive-bitrate/design.md +92 -92
  30. package/openspec/changes/adaptive-bitrate/proposal.md +56 -56
  31. package/openspec/changes/adaptive-bitrate/specs/adaptive-bitrate/spec.md +51 -51
  32. package/openspec/changes/adaptive-bitrate/tasks.md +40 -40
  33. package/openspec/changes/binary-distribution/.openspec.yaml +2 -2
  34. package/openspec/changes/binary-distribution/proposal.md +53 -53
  35. package/openspec/changes/chunked-request-bodies/design.md +81 -81
  36. package/openspec/changes/chunked-request-bodies/proposal.md +53 -53
  37. package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -30
  38. package/openspec/changes/chunked-request-bodies/tasks.md +40 -40
  39. package/openspec/changes/cold-start/design.md +98 -98
  40. package/openspec/changes/cold-start/proposal.md +62 -62
  41. package/openspec/changes/cold-start/specs/cold-start/spec.md +47 -47
  42. package/openspec/changes/cold-start/tasks.md +48 -48
  43. package/openspec/changes/disk-cap/.openspec.yaml +2 -2
  44. package/openspec/changes/disk-cap/proposal.md +37 -37
  45. package/openspec/changes/disk-cap/specs/disk-cap/spec.md +25 -25
  46. package/openspec/changes/disk-cap/tasks.md +19 -19
  47. package/openspec/changes/proxy-observability/.openspec.yaml +2 -2
  48. package/openspec/changes/proxy-observability/design.md +38 -38
  49. package/openspec/changes/proxy-observability/proposal.md +49 -49
  50. package/openspec/changes/proxy-observability/specs/observability/spec.md +33 -33
  51. package/openspec/changes/proxy-observability/tasks.md +21 -21
  52. package/openspec/changes/seek-debounce/design.md +118 -118
  53. package/openspec/changes/seek-debounce/proposal.md +59 -59
  54. package/openspec/changes/seek-debounce/specs/seek-debounce/spec.md +41 -41
  55. package/openspec/changes/seek-debounce/tasks.md +33 -33
  56. package/openspec/changes/subtitle-language/.openspec.yaml +2 -2
  57. package/openspec/changes/subtitle-language/proposal.md +50 -50
  58. package/openspec/changes/subtitle-language/specs/subtitle-language/spec.md +34 -34
  59. package/openspec/changes/subtitle-language/tasks.md +26 -26
  60. package/openspec/changes/track-selection/.openspec.yaml +2 -2
  61. package/openspec/changes/track-selection/design.md +47 -47
  62. package/openspec/changes/track-selection/proposal.md +45 -45
  63. package/openspec/changes/track-selection/specs/track-selection/spec.md +41 -41
  64. package/openspec/changes/track-selection/tasks.md +20 -20
  65. package/openspec/changes/transcode-quality/.openspec.yaml +2 -2
  66. package/openspec/changes/transcode-quality/proposal.md +51 -51
  67. package/openspec/changes/transcode-quality/specs/transcode-quality/spec.md +139 -139
  68. package/openspec/changes/transcode-quality/tasks.md +63 -63
  69. package/openspec/config.yaml +38 -38
  70. package/package.json +1 -1
  71. package/public/.well-known/appspecific/com.chrome.devtools.json +1 -1
  72. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  73. package/research/double-spawn-2026-09-10.md +171 -171
  74. package/research/handover-2026-09-13.md +209 -209
  75. package/research/handover-reader-claims-removal-2026-09-12.md +166 -166
  76. package/research/piece-withdrawn-but-still-claimed-2026-09-12.md +175 -175
  77. package/research/preset-benchmark-size-scaling-2026-08-22.md +55 -55
  78. package/research/priority-map-is-the-truth-2026-09-12.md +225 -225
  79. package/routes/api/client-logs/post.js +86 -86
  80. package/routes/api/delivery-sink/get.js +72 -72
  81. package/routes/api/link-probe/get.js +51 -51
  82. package/routes/api/playback-plan/audio-tracks/post.js +29 -29
  83. package/routes/api/playback-plan/post.js +53 -53
  84. package/routes/api/sources/post.js +36 -36
  85. package/routes/api/sources/stats/get.js +132 -132
  86. package/routes/api/sources/warm/post.js +217 -217
  87. package/routes/api/subtitles/get.js +230 -230
  88. package/routes/api/transcode-sessions/fragment-far/post.js +60 -60
  89. package/routes/api/transcode-sessions/net-report/post.js +138 -138
  90. package/routes/api/transcode-sessions/post.js +178 -178
  91. package/routes/api/transcode-sessions/progress/get.js +27 -27
  92. package/routes/api/transcode-sessions/release/post.js +41 -41
  93. package/routes/api/transcode-sessions/seek/post.js +63 -63
  94. package/routes/health/get.js +13 -13
  95. package/routes/healthz/get.js +13 -13
  96. package/routes/stream/get.js +416 -416
  97. package/routes/transcode/audio-file/get.js +64 -64
  98. package/routes/transcode/audio-warm/get.js +95 -95
  99. package/routes/transcode/session-file/get.js +52 -52
  100. package/routes/transcode/variant-file/get.js +95 -95
  101. package/routes/transcode/variant-warm/get.js +84 -84
  102. package/scripts/render-run-graph.js +173 -173
  103. package/server.js +748 -748
  104. package/services/encode/CoverageMap.js +428 -428
  105. package/services/encode/CushionReport.js +345 -345
  106. package/services/encode/EncodeAdmission.js +376 -376
  107. package/services/encode/EncodeOrchestrator.js +1192 -1192
  108. package/services/encode/EncodePlan.js +1368 -1368
  109. package/services/encode/EncodeRun.js +32 -4
  110. package/services/encode/EncodeRuns.js +19 -7
  111. package/services/encode/Encoder.js +142 -142
  112. package/services/encode/EncoderSelection.js +38 -38
  113. package/services/encode/LocalObservations.js +359 -359
  114. package/services/encode/NvencEncoder.js +50 -50
  115. package/services/encode/OutputTimes.js +579 -579
  116. package/services/encode/QsvEncoder.js +58 -58
  117. package/services/encode/Renditions.js +2283 -2283
  118. package/services/encode/RunClock.js +87 -87
  119. package/services/encode/RunProgress.js +79 -79
  120. package/services/encode/SegmentDemand.js +95 -95
  121. package/services/encode/SoftwareEncoder.js +121 -121
  122. package/services/encode/V4l2m2mEncoder.js +53 -53
  123. package/services/encode/VaapiEncoder.js +66 -66
  124. package/services/encode/args.js +418 -418
  125. package/services/encode/available-share.js +89 -89
  126. package/services/encode/calibration.js +361 -361
  127. package/services/encode/contention.js +128 -128
  128. package/services/encode/decode-cost-fit.js +363 -363
  129. package/services/encode/encode-exit.js +116 -114
  130. package/services/encode/encode-run-state.js +551 -551
  131. package/services/encode/encoder-readings.js +43 -43
  132. package/services/encode/fingerprint.js +322 -322
  133. package/services/encode/host-load.js +174 -174
  134. package/services/encode/index.js +9 -9
  135. package/services/encode/learned-median.js +90 -90
  136. package/services/encode/output/EncodedOutput.js +57 -57
  137. package/services/encode/output/Output.js +131 -131
  138. package/services/encode/output/OutputCatalog.js +414 -414
  139. package/services/encode/output/OutputSpec.js +390 -390
  140. package/services/encode/output/Timeline.js +308 -308
  141. package/services/encode/output/cut-grid.js +107 -107
  142. package/services/encode/output/ladder.js +32 -32
  143. package/services/encode/output/playlists.js +284 -284
  144. package/services/encode/output/rates.js +125 -125
  145. package/services/encode/output-key-format.js +21 -21
  146. package/services/encode/piece-completeness.js +60 -2
  147. package/services/encode/quality/EncodeCost.js +1043 -1043
  148. package/services/encode/quality/HostLoad.js +525 -525
  149. package/services/encode/quality/HostTimings.js +249 -249
  150. package/services/encode/quality/OutputQualityState.js +24 -24
  151. package/services/encode/quality/QualityController.js +758 -758
  152. package/services/encode/quality/QualityOffer.js +416 -416
  153. package/services/encode/quality/drain-threat.js +47 -47
  154. package/services/encode/quality/link-budget.js +337 -337
  155. package/services/encode/quality/output-format.js +319 -319
  156. package/services/encode/quality/serving-output.js +216 -216
  157. package/services/encode/quality/visible-rung.js +57 -57
  158. package/services/encode/run-budget.js +97 -97
  159. package/services/encode/run-command.js +3 -1
  160. package/services/encode/run-costs.js +155 -155
  161. package/services/encode/run-inputs.js +53 -53
  162. package/services/encode/segment-formats/fmp4.js +476 -476
  163. package/services/encode/segment-formats/index.js +1 -0
  164. package/services/encode/segment-formats/init-compat.js +324 -324
  165. package/services/encode/segment-formats/mp4-boxes.js +8 -1
  166. package/services/encode/segment-formats/mpegts.js +134 -134
  167. package/services/encode/start-stop-cost.js +178 -178
  168. package/services/encode/throughput.js +97 -97
  169. package/services/encode/torrent-cost.js +88 -88
  170. package/services/identity/installation-id.js +38 -38
  171. package/services/media/SourceFile.js +298 -298
  172. package/services/media/SubtitleOrchestrator.js +167 -167
  173. package/services/media/container/KeyframeTable.js +272 -272
  174. package/services/media/container/ebml-reader.js +159 -159
  175. package/services/media/ffmpeg-banner.js +260 -260
  176. package/services/media/keyframe-probe.js +157 -157
  177. package/services/media/media-info-probe.js +93 -93
  178. package/services/media/playback-planner.js +931 -931
  179. package/services/media/tracks/AudioTrack.js +143 -143
  180. package/services/media/tracks/ImageSubtitleTrack.js +19 -19
  181. package/services/media/tracks/SubtitleTrack.js +38 -38
  182. package/services/media/tracks/VideoTrack.js +33 -33
  183. package/services/media/tracks/audio-bound.js +233 -233
  184. package/services/media/tracks/index.js +15 -15
  185. package/services/media/tracks/language-detect.js +174 -174
  186. package/services/server/OutputLifecycle.js +418 -418
  187. package/services/server/SegmentServing.js +1152 -1152
  188. package/services/server/ViewerRequests.js +785 -785
  189. package/services/server/WaitLedger.js +142 -142
  190. package/services/server/controllers/PlaybackController.js +40 -40
  191. package/services/server/controllers/SubtitleController.js +109 -109
  192. package/services/server/http-responses.js +60 -60
  193. package/services/server/transcode-session-files.js +325 -325
  194. package/services/server/wire-outputs.js +1029 -1029
  195. package/services/storage/Diagnostics.js +202 -202
  196. package/services/storage/MachineBudget.js +235 -235
  197. package/services/storage/allowance.js +107 -107
  198. package/services/storage/core-dumps.js +106 -106
  199. package/services/storage/files/CompletedFiles.js +391 -391
  200. package/services/storage/files/piece-from-whole-file.js +118 -118
  201. package/services/storage/free.js +71 -71
  202. package/services/storage/keep.js +48 -48
  203. package/services/storage/machine-memory.js +56 -56
  204. package/services/storage/memory-report.js +575 -575
  205. package/services/storage/piece-store/piece-disk-store.js +539 -539
  206. package/services/storage/piece-store/piece-lru.js +495 -495
  207. package/services/storage/returns.js +103 -103
  208. package/services/storage/wire.js +175 -175
  209. package/services/torrent/demand/DemandRegister.js +202 -202
  210. package/services/torrent/demand/Urgency.js +137 -137
  211. package/services/torrent/demand/Window.js +118 -118
  212. package/services/torrent/demand/index.js +8 -8
  213. package/services/torrent/demand/pieces.js +140 -140
  214. package/services/torrent/download/SwarmSelection.js +386 -386
  215. package/services/torrent/download/registry.js +102 -102
  216. package/services/torrent/download/withdraw-claim.js +80 -80
  217. package/services/torrent/files.js +455 -455
  218. package/services/torrent/naming.js +619 -619
  219. package/services/torrent/piece-store-of.js +29 -29
  220. package/services/torrent/supply-margin.js +264 -264
  221. package/services/torrent/worker/background-fill.js +213 -213
  222. package/services/torrent/worker/channel.js +271 -271
  223. package/services/torrent/worker/fastest-wires.js +342 -342
  224. package/services/torrent/worker/handle-state.js +23 -23
  225. package/services/torrent/worker/install-webrtc-shim.js +32 -32
  226. package/services/torrent/worker/piece-reader.js +1078 -1078
  227. package/services/torrent/worker/pool-adapter.js +371 -371
  228. package/services/torrent/worker/protocol.js +184 -184
  229. package/services/torrent/worker/resume-warm.js +107 -107
  230. package/services/torrent/worker/webrtc-shim.js +219 -219
  231. package/services/transport/delivery-probe.js +842 -842
  232. package/services/transport/health-collector.js +53 -53
  233. package/services/transport/nat-classifier.js +231 -231
  234. package/services/transport/packet-witness.js +808 -808
  235. package/services/transport/port-mapper.js +235 -235
  236. package/services/transport/registry-api.js +81 -81
  237. package/services/transport/tunnel-client.js +447 -447
  238. package/services/transport/usrsctp-state.js +175 -175
  239. package/services/transport/webrtc-manager.js +484 -484
  240. package/services/viewer/Assignments.js +340 -340
  241. package/services/viewer/PriorityOrchestrator.js +325 -325
  242. package/services/viewer/Viewer.js +691 -691
  243. package/services/viewer/Viewers.js +368 -368
  244. package/services/viewer/active-output.js +37 -37
  245. package/services/viewer/audio-start.js +46 -46
  246. package/services/viewer/buffer-trend.js +81 -81
  247. package/services/viewer/choices.js +647 -647
  248. package/services/viewer/media-time.js +355 -355
  249. package/services/viewer/playback-readiness.js +635 -635
  250. package/services/viewer/positions.js +126 -126
  251. package/services/viewer/report-intake.js +46 -46
  252. package/store/source-registry.js +71 -71
  253. package/test/asset-paths.test.js +28 -28
  254. package/test/audio-buffer-continuity.test.js +77 -77
  255. package/test/audio-inventory.test.js +212 -212
  256. package/test/audio-track-bitrate.test.js +40 -40
  257. package/test/auto-quality-step.test.js +762 -753
  258. package/test/available-share.test.js +76 -76
  259. package/test/background-fill.test.js +190 -190
  260. package/test/client-log-file.test.js +110 -110
  261. package/test/completed-files.test.js +115 -115
  262. package/test/concurrent-cost.test.js +148 -148
  263. package/test/container-media-info.test.js +228 -228
  264. package/test/contention.test.js +76 -76
  265. package/test/core-dumps.test.js +57 -57
  266. package/test/coverage-follows-the-disk.test.js +228 -228
  267. package/test/coverage-map.test.js +195 -195
  268. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  269. package/test/cut-times-timeline.test.js +65 -65
  270. package/test/cuts-follow-published-grid.test.js +109 -109
  271. package/test/data-channel-frame.test.js +63 -63
  272. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  273. package/test/dead-torrent-handle.test.js +52 -52
  274. package/test/declared-rates.test.js +116 -116
  275. package/test/declared-tracks.test.js +43 -43
  276. package/test/decode-cost-fit.test.js +202 -202
  277. package/test/decode-cost.test.js +475 -462
  278. package/test/delivery-probe.test.js +393 -393
  279. package/test/demand-register.test.js +206 -206
  280. package/test/dht-bootstrap.test.js +72 -72
  281. package/test/drain-threat.test.js +65 -65
  282. package/test/duplicate-add.test.js +48 -48
  283. package/test/encode-admission.test.js +146 -146
  284. package/test/encode-cost.test.js +275 -275
  285. package/test/encode-exit.test.js +111 -111
  286. package/test/encode-orchestrator.test.js +426 -426
  287. package/test/encode-plan-viewers.test.js +725 -725
  288. package/test/encode-plan.test.js +545 -545
  289. package/test/encode-run-state.test.js +314 -314
  290. package/test/encode-run.test.js +38 -0
  291. package/test/encode-slope.test.js +46 -46
  292. package/test/encoded-output.test.js +39 -39
  293. package/test/encoder-kinds.test.js +122 -122
  294. package/test/encoder-readings.test.js +68 -68
  295. package/test/every-claimant-is-told-its-share.test.js +152 -152
  296. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  297. package/test/failed-start-breaker.test.js +202 -202
  298. package/test/fastest-wires.test.js +143 -143
  299. package/test/ffmpeg-stream-counts.test.js +78 -78
  300. package/test/file-edges.test.js +191 -191
  301. package/test/fixtures/refused-audio-20261002.json +10 -0
  302. package/test/fmp4-presentation-clock.test.js +4 -2
  303. package/test/fmp4-self-contained.test.js +80 -80
  304. package/test/fmp4-timestamps.test.js +140 -140
  305. package/test/fmp4-track-completeness.test.js +41 -41
  306. package/test/format-keyed-outputs.test.js +78 -78
  307. package/test/health-metrics.test.js +38 -38
  308. package/test/held-request-width.test.js +157 -157
  309. package/test/helpers/encode-run.js +240 -240
  310. package/test/helpers/manager.js +62 -57
  311. package/test/helpers/output-spec.js +63 -63
  312. package/test/host-load.test.js +68 -68
  313. package/test/index-accuracy-is-about-the-file.test.js +128 -128
  314. package/test/init-compat.test.js +219 -219
  315. package/test/input-lost-quiets-the-plan.test.js +261 -261
  316. package/test/input-unavailable.test.js +48 -48
  317. package/test/installation-id.test.js +39 -39
  318. package/test/keeping-period.test.js +83 -83
  319. package/test/keyframe-index-accuracy.test.js +188 -188
  320. package/test/keyframes-belong-to-the-file.test.js +249 -249
  321. package/test/learned-median.test.js +37 -37
  322. package/test/letting-go-asks-who-is-watching.test.js +191 -191
  323. package/test/limit-row-by-area.test.js +60 -60
  324. package/test/link-budget.test.js +111 -111
  325. package/test/link-probe.test.js +56 -56
  326. package/test/local-encoding-data.test.js +273 -273
  327. package/test/logger-repeats.test.js +134 -134
  328. package/test/look-ahead-coverage.test.js +56 -56
  329. package/test/manager-surface.test.js +291 -291
  330. package/test/matroska-cues-track.test.js +192 -192
  331. package/test/media-time.test.js +62 -62
  332. package/test/memory-budget.test.js +390 -390
  333. package/test/move-cost.test.js +216 -216
  334. package/test/mp4-subtitles.test.js +173 -173
  335. package/test/one-authority.test.js +285 -285
  336. package/test/one-budget.test.js +149 -149
  337. package/test/one-resource-divided.test.js +185 -185
  338. package/test/one-serving-output-per-height.test.js +458 -458
  339. package/test/orchestrator-wired.test.js +207 -207
  340. package/test/output-catalog.test.js +39 -39
  341. package/test/output-shape.test.js +21 -21
  342. package/test/output-spec.test.js +251 -251
  343. package/test/output-speed.test.js +87 -87
  344. package/test/outputs-being-prepared.test.js +40 -40
  345. package/test/packet-witness-ring.test.js +236 -236
  346. package/test/packet-witness.test.js +148 -148
  347. package/test/piece-completeness.test.js +37 -1
  348. package/test/piece-disk-store.test.js +401 -401
  349. package/test/piece-from-whole-file.test.js +129 -129
  350. package/test/piece-lru.test.js +319 -319
  351. package/test/piece-reader.test.js +162 -162
  352. package/test/piece-selection-offset.test.js +85 -85
  353. package/test/piece-store-eviction.test.js +595 -595
  354. package/test/piece-store-never-refuses.test.js +153 -153
  355. package/test/piece-store-reservations.test.js +403 -403
  356. package/test/piece-store-slow-disk.test.js +159 -159
  357. package/test/piece-tail.test.js +97 -97
  358. package/test/plan-host-timings.test.js +68 -68
  359. package/test/plan-is-steady.test.js +225 -225
  360. package/test/playback-readiness.test.js +518 -518
  361. package/test/playback-start-regressions.test.js +101 -101
  362. package/test/priority-map-download.test.js +174 -174
  363. package/test/priority-map-emptied.test.js +204 -204
  364. package/test/priority-map-per-output.test.js +215 -215
  365. package/test/priority-map.test.js +163 -163
  366. package/test/probe-wedge-certainty.test.js +60 -60
  367. package/test/produced-copy-choice.test.js +213 -213
  368. package/test/published-timeline.test.js +83 -83
  369. package/test/quality-offer.test.js +160 -160
  370. package/test/quality-variants.test.js +1270 -1257
  371. package/test/rate-control-in-the-output.test.js +180 -180
  372. package/test/read-survives-withdrawal.test.js +164 -164
  373. package/test/read-window.test.js +365 -365
  374. package/test/resume-warm.test.js +39 -39
  375. package/test/run-graph-drift.test.js +37 -37
  376. package/test/run-inputs.test.js +80 -80
  377. package/test/run-intervals.test.js +100 -100
  378. package/test/run-position-follows-published-grid.test.js +89 -89
  379. package/test/run-progress.test.js +64 -64
  380. package/test/same-height-switch.test.js +663 -663
  381. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  382. package/test/seek-landing.test.js +109 -109
  383. package/test/seek-target-not-superseded.test.js +195 -195
  384. package/test/segment-cut-times.test.js +63 -63
  385. package/test/segment-demand.test.js +80 -80
  386. package/test/segment-hold-supersede.test.js +91 -91
  387. package/test/segment-judged-by-its-own-header.test.js +222 -221
  388. package/test/segment-serve-wiring.test.js +9 -3
  389. package/test/segment-store-eviction.test.js +247 -247
  390. package/test/segment-store.test.js +352 -352
  391. package/test/segment-true-start.test.js +86 -86
  392. package/test/segments-are-shared.test.js +176 -176
  393. package/test/send-chunk-bytes.test.js +86 -86
  394. package/test/serving-existing-output.test.js +111 -105
  395. package/test/serving-output.test.js +102 -102
  396. package/test/shared-piece-store.test.js +310 -310
  397. package/test/sidecar-naming.test.js +142 -142
  398. package/test/soundtrack-rate-bound.test.js +289 -289
  399. package/test/source-file.test.js +133 -133
  400. package/test/source-registry.test.js +18 -18
  401. package/test/split-a-stretch.test.js +139 -139
  402. package/test/stale-request-after-seek.test.js +158 -158
  403. package/test/startup-readings.test.js +124 -124
  404. package/test/stream-route.test.js +237 -237
  405. package/test/subtitle-cue-framing.test.js +200 -200
  406. package/test/subtitle-cue-source.test.js +102 -102
  407. package/test/subtitle-cursor.test.js +63 -63
  408. package/test/subtitle-defaults.test.js +118 -118
  409. package/test/subtitle-language.test.js +252 -252
  410. package/test/supply-margin.test.js +190 -190
  411. package/test/swarm-follows-readers.test.js +174 -174
  412. package/test/swarm-reach.test.js +130 -130
  413. package/test/swarm-selection.test.js +220 -220
  414. package/test/tail-duplication.test.js +167 -167
  415. package/test/the-channel-has-both-ends.test.js +91 -91
  416. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  417. package/test/thread-pool.test.js +53 -53
  418. package/test/timeline.test.js +84 -84
  419. package/test/torrent-contents.test.js +235 -235
  420. package/test/torrent-cost.test.js +71 -71
  421. package/test/torrent-files.test.js +221 -221
  422. package/test/torrent-naming.test.js +255 -255
  423. package/test/tracks-begin-together.test.js +209 -209
  424. package/test/tunnel-renewal.test.js +167 -167
  425. package/test/two-viewers-one-picture.test.js +508 -504
  426. package/test/upload-hurry.test.js +186 -186
  427. package/test/usrsctp-state.test.js +131 -131
  428. package/test/video-facts.test.js +102 -102
  429. package/test/viewer-assignments.test.js +143 -143
  430. package/test/viewer-outputs.test.js +285 -285
  431. package/test/viewer-presence.test.js +116 -116
  432. package/test/viewer-requests-admission.test.js +92 -89
  433. package/test/viewer-states.test.js +189 -189
  434. package/test/viewer-subtitle-subscription.test.js +96 -96
  435. package/test/viewer.test.js +139 -139
  436. package/test/viewing-generations.test.js +390 -390
  437. package/test/visible-rung.test.js +37 -37
  438. package/test/wait-ledger.test.js +100 -100
  439. package/test/webrtc-shim.test.js +149 -149
  440. package/test/wedge-certainty.test.js +131 -131
  441. package/test/withdraw-piece-claim.test.js +212 -212
  442. package/test/worker-channel.test.js +158 -158
  443. package/utils/client-log-file.js +151 -151
  444. package/utils/logger.js +312 -312
  445. package/utils/parse-range.js +25 -25
  446. package/utils/perf.js +59 -59
  447. package/utils/torrent-source-key.js +38 -38
@@ -1,1192 +1,1192 @@
1
- /**
2
- * @file How many encoders run on this proxy, on which outputs, and over which
3
- * stretches.
4
- *
5
- * The application layer over `encode/`. It holds four things and owns none of
6
- * their rules:
7
- *
8
- * 1. what viewers want (`SegmentDemand`), stated once each and read as a union;
9
- * 2. what has been made and what is being made, one `CoverageMap` per output;
10
- * 3. the encoders that are running (`EncodeRun`), each over a stretch;
11
- * 4. a tally of how every run ended, which is what makes "abnormal endings do
12
- * not happen" a number rather than an impression.
13
- *
14
- * The decision itself is `EncodePlan.planEncoders`, from numbers alone. This
15
- * carries it out, and everything it cannot know is injected: how many encoders
16
- * this machine can afford, how a run is built for a given stretch, and which
17
- * segments already exist.
18
- *
19
- * **No viewer reaches the decision.** A viewer states a window and is forgotten
20
- * as a name; what the plan sees is a union of windows. That is the rule the
21
- * layer exists for, stated by the user 2026-09-04: requests come from any
22
- * viewers in any number, encoders are managed to suit them, and viewers get the
23
- * result when it is ready.
24
- */
25
-
26
- import { CoverageMap } from "./CoverageMap.js";
27
- import { firstUnmetWant, planEncoders } from "./EncodePlan.js";
28
- import { endOfRun } from "./EncodeRun.js";
29
- import { ENCODE_EXIT } from "./encode-exit.js";
30
- import { affordableRuns } from "./run-budget.js";
31
- import { RunCosts } from "./run-costs.js";
32
- import { contentionPenalty } from "./contention.js";
33
- import { SegmentDemand } from "./SegmentDemand.js";
34
- import { runStateOf } from "./encode-run-state.js";
35
-
36
- /**
37
- * @typedef {Object} SegmentCoverage
38
- * @property {(address: string) => number[]} provenNumbers
39
- * @property {(address: string, index: number) => void} announce
40
- * @property {(address: string) => number} filesHeld
41
- * @property {(address: string, startedAt: number) => number} clearUpAfter
42
- */
43
-
44
- /**
45
- * How long nothing is placed on an output whose input has just gone, and the
46
- * ceiling that doubling reaches.
47
- *
48
- * Both are chosen, and are named here as chosen rather than dressed as
49
- * measurements: what they bound is not how long the data takes to come back —
50
- * that is the swarm's business and nobody here can know it — but how often it
51
- * is worth asking. They replace the same two figures, with the same values,
52
- * that lived in the session manager and governed only the dead run's own retry
53
- * while the plan placed fresh runs beside it every half second.
54
- */
55
- const INPUT_QUIET_BASE_MS = 2_000;
56
- const INPUT_QUIET_MAX_MS = 15_000;
57
- const START_FAST_FAIL_MS = 2_000;
58
- const MAX_FAILED_STARTS = 3;
59
-
60
- export class EncodeOrchestrator {
61
- /** Derived priority maps. Discardable and rebuilt from viewer state. */
62
- #demand = new SegmentDemand();
63
- /** @type {(address: string) => string} */
64
- #describeWaits = () => "";
65
-
66
- /** Output address to what has been made of it. @type {Map<string, CoverageMap>} */
67
- #coverage = new Map();
68
-
69
- /** @type {SegmentCoverage | null} */
70
- #segmentCoverage = null;
71
-
72
- /** Output address to the runs on it. @type {Map<string, import("../encode/EncodeRun.js").EncodeRun[]>} */
73
- #runs = new Map();
74
-
75
- /** Last state after an output has no registered run. @type {Map<string, string>} */
76
- #lastState = new Map();
77
-
78
- /** Last encoder error per output. @type {Map<string, string>} */
79
- #lastError = new Map();
80
-
81
- /** Last progress snapshot per output after its run ends. @type {Map<string, object>} */
82
- #lastProgress = new Map();
83
-
84
- /** Consecutive fast failures at one position, per output. @type {Map<string, { at: number, count: number }>} */
85
- #failedStarts = new Map();
86
-
87
- /** How runs have ended, by cause. @type {Map<string, number>} */
88
- #endings = new Map();
89
-
90
- /**
91
- * How many times in a row an output's run has died because its input was not
92
- * there. Cleared only by a run that PRODUCED something, which is the only
93
- * proof that the input can be read — see `#noteInputAvailability`.
94
- *
95
- * @type {Map<string, number>}
96
- */
97
- #inputLostAttempts = new Map();
98
-
99
- /** Output address to the time before which nothing is placed on it. @type {Map<string, number>} */
100
- #quietUntil = new Map();
101
-
102
- /** The wake-up per output, so a quiet output is reconsidered. @type {Map<string, NodeJS.Timeout>} */
103
- #quietTimers = new Map();
104
-
105
- /** The last state said out loud, so an unchanged state is not repeated. */
106
- #lastDescribed = "";
107
-
108
- /** What a stop and a start have cost on this host. */
109
- #costs = new RunCosts();
110
-
111
- /**
112
- * What starting and stopping an encoder was measured to cost on this host,
113
- * before any viewer existed. Told once; real runs replace it as they end.
114
- *
115
- * @param {{ firstByteWaitSec: number, killCostSec: number } | null} measured
116
- * @returns {void}
117
- */
118
- noteStartupCosts(measured) {
119
- this.#costs.noteStartup(measured);
120
- }
121
-
122
- /** Derived segment demand for one output, copied from the discardable cache. */
123
- wantedSegmentsOn(address) {
124
- return [...this.#demand.mapOn(address)];
125
- }
126
-
127
- /** The last reason a budget was cut, so the same one is not said twice. */
128
- #lastBudgetReason = new Map();
129
-
130
- /** The last unmet want said out loud, so a stuck one is said once. */
131
- #lastUnmet = new Map();
132
-
133
- /** The last time the machine bound an output's encoders, so it is said once. */
134
- #lastMachineBound = new Map();
135
-
136
- /**
137
- * @param {object} params
138
- * @param {(address: string) => number} params.maxRunsFor - How many encoders
139
- * this machine can afford on one output. The same arithmetic that decides
140
- * the quality offer; measured per host, never chosen here.
141
- * @param {(params: { address: string, from: number, to: number, because: string }) =>
142
- * import("../encode/EncodeRun.js").EncodeRun} params.makeRun - Build a run
143
- * for a stretch. What to read, what to map and how to cut belong to whoever
144
- * knows the source.
145
- * @param {number} params.segmentSeconds
146
- * @param {import("../encode/contention.js").ContentionPenalties | null}
147
- * [params.contentionPenalties] - How much slower one encoder runs beside
148
- * others, MEASURED on this host at startup and keyed by how many others
149
- * there are. Null until something has measured it, and then the penalty is
150
- * 1 — a number invented here would be the same mistake as an invented
151
- * encoding speed.
152
- * @param {{ info: (line: string) => void, warn: (line: string) => void }} params.logger
153
- * @param {() => number} [params.now]
154
- * @param {(address: string) => string} [params.describeWaits] - What the
155
- * viewers actually waited for on this output, by band, for the state line.
156
- * HANDED IN: what anybody waited for belongs to the priority layer, and
157
- * this one may be asked about encoders with no ledger, no clock and no
158
- * viewer anywhere. Absent, the line simply does not carry it.
159
- * @param {SegmentCoverage | null} [params.segmentCoverage]
160
- */
161
- constructor({
162
- maxRunsFor,
163
- makeRun,
164
- segmentSeconds,
165
- contentionPenalties = null,
166
- refetchSecPerFilmSecond = () => 0,
167
- startingSpeedFor = () => 0,
168
- segmentCoverage = null,
169
- planSoon = null,
170
- describeWaits = null,
171
- admission = null,
172
- logger,
173
- now
174
- }) {
175
- // HOW MANY ENCODERS THE WHOLE MACHINE HOLDS, across outputs. `maxRunsFor`
176
- // answers for one output as though it were alone; this is what refuses the
177
- // encoder that would slow everybody below realtime. Absent in a check that
178
- // is about one output, and then only the per-output limit binds.
179
- this.admission = admission && typeof admission.placesFor === "function" ? admission : null;
180
- this.#describeWaits = typeof describeWaits === "function" ? describeWaits : () => "";
181
- // Only the segment facts and operations this planner needs cross the
182
- // storage boundary; the concrete storage remains in the server assembly.
183
- this.#segmentCoverage = segmentCoverage;
184
- this.maxRunsFor = maxRunsFor;
185
- // Seconds of swarm time per second of film: what re-encoding material that
186
- // already exists costs the download, over and above the encoder's own time.
187
- // Injected, because the film's byte rate and the swarm's are measured
188
- // elsewhere and this class must not reach for them.
189
- this.refetchSecPerFilmSecond = refetchSecPerFilmSecond;
190
- // Measured per host: what a second encoder costs the first. Unmeasured is 1,
191
- // and then only the budget bounds how many there are.
192
- this.contentionPenalties = contentionPenalties instanceof Map ? contentionPenalties : null;
193
- // WHAT THIS HOST ENCODES AT BEFORE ANY RUN HAS REPORTED. The startup
194
- // benchmark measures it — a real pipeline over real clips, before a viewer
195
- // exists — so the plan is never asked to compare arrivals with no speed to
196
- // compute them from. Every run that then works refines it.
197
- this.startingSpeedFor = startingSpeedFor;
198
- this.makeRun = makeRun;
199
- this.segmentSeconds = segmentSeconds;
200
- this.logger = logger;
201
- this.now = typeof now === "function" ? now : Date.now;
202
- // Asked for, not commanded: this class decides, and something else owns the
203
- // loop that calls it. Absent in a test, where the clock is the test's own.
204
- this.planSoon = typeof planSoon === "function" ? planSoon : () => undefined;
205
- }
206
-
207
- /**
208
- * The map of one output, made on first mention.
209
- *
210
- * @param {string} address
211
- * @returns {CoverageMap}
212
- */
213
- coverageOf(address) {
214
- let map = this.#coverage.get(address);
215
- if (!map) {
216
- map = new CoverageMap();
217
- this.#coverage.set(address, map);
218
- }
219
- return map;
220
- }
221
-
222
- /**
223
- * Put the map's picture of what is ready back in step with the disk.
224
- *
225
- * ONE AUTHORITY ON WHAT EXISTS, AND IT IS THE STORE. The map holds no memory
226
- * of readiness between calls: it is handed the whole answer, replacing
227
- * whatever it had, immediately before anything is decided from it. So a
228
- * segment whose file was discarded with the run that had it open, dropped to
229
- * make room, or reopened by a run restarting on it stops being ready in the
230
- * same breath — without anything having to notice and say so.
231
- *
232
- * The map used to be filled from outside, by the session manager, with a
233
- * method that only ever added. Nothing anywhere took a number back. Field
234
- * 2026-09-07: the map claimed all 482 segments of a film while the directory
235
- * held nothing, so every arrangement scored perfect, the only encoder was
236
- * stopped as unnecessary and none was placed again — two sessions in a row
237
- * with no picture at all.
238
- *
239
- * A store is optional here only in the sense that an authority which was not
240
- * supplied cannot be consulted: without one the map keeps what it was told
241
- * directly, which is how this class is exercised with plain numbers.
242
- *
243
- * @param {string} address
244
- * @returns {CoverageMap}
245
- */
246
- #upToDateCoverage(address) {
247
- const coverage = this.coverageOf(address);
248
- if (this.#segmentCoverage) {
249
- coverage.setReady(this.#segmentCoverage.provenNumbers(address));
250
- }
251
- return coverage;
252
- }
253
-
254
- /**
255
- * Where a run started here must stop: the free stretch in front of it.
256
- *
257
- * Asked of the one map, brought up to date first. It used to be worked out by
258
- * the session manager, which reached into this layer for the map and into the
259
- * store for what was on the disk and put the two together itself — one fact
260
- * with two owners and a third party carrying it between them, which is how the
261
- * two came to disagree.
262
- *
263
- * @param {object} params
264
- * @param {string} params.address
265
- * @param {number} params.from - Where the run will start.
266
- * @param {object | null} [params.exceptRun] - The run being replaced, whose
267
- * own claim is not somebody else's material.
268
- * @param {number} [params.segmentCount] - The output's length, when known.
269
- * @returns {number} The last number to work through, or `-1` for the end of
270
- * the film.
271
- */
272
- freeStretchEnd({ address, from, exceptRun = null, segmentCount = 0 }) {
273
- if (!address) {
274
- return -1;
275
- }
276
- if (segmentCount > 0) {
277
- this.coverageOf(address).setSegmentCount(segmentCount);
278
- }
279
- const coverage = this.#upToDateCoverage(address);
280
- const start = Math.max(0, from);
281
- const free = coverage.freeRunFrom(start, exceptRun);
282
- if (!Number.isFinite(free)) {
283
- return -1;
284
- }
285
- const end = start + Math.max(1, free) - 1;
286
- return segmentCount > 0 && end >= segmentCount - 1 ? -1 : end;
287
- }
288
-
289
- /**
290
- * @param {string} address
291
- * @returns {import("../encode/EncodeRun.js").EncodeRun[]}
292
- */
293
- runsOn(address) {
294
- return this.#runs.get(address) ?? [];
295
- }
296
-
297
- /**
298
- * The aggregate state of this output's current runs, or its last ending when
299
- * none remain.
300
- *
301
- * @param {string} address
302
- * @returns {string}
303
- */
304
- stateOf(address) {
305
- const runs = this.runsOn(address);
306
- return runs.length > 0 ? runStateOf(runs) : (this.#lastState.get(address) ?? runStateOf([]));
307
- }
308
-
309
- /** @param {string} address @returns {string} */
310
- errorOf(address) {
311
- return this.#lastError.get(address) ?? "";
312
- }
313
-
314
- /**
315
- * Progress of the live run that covers a position, or the most recently
316
- * updated run when no position is supplied.
317
- *
318
- * @param {string} address
319
- * @param {number | null} [index]
320
- * @returns {object | null}
321
- */
322
- progressOf(address, index = null) {
323
- const live = this.runsOn(address).filter((run) => run.isAlive);
324
- const covering = Number.isInteger(index)
325
- ? live.filter((run) => run.from <= index && endOfRun(run) >= index)
326
- : live;
327
- const candidates = covering.length > 0 ? covering : live;
328
- const run = [...candidates].sort(
329
- (left, right) => (right.progress?.updatedAt ?? 0) - (left.progress?.updatedAt ?? 0)
330
- )[0];
331
- return run?.progress?.snapshot?.() ?? this.#lastProgress.get(address) ?? null;
332
- }
333
-
334
- /**
335
- * Whether another start at this position is allowed.
336
- *
337
- * @param {string} address
338
- * @param {number} from
339
- * @returns {boolean}
340
- */
341
- mayStartAt(address, from) {
342
- const failed = this.#failedStarts.get(address);
343
- return failed?.at !== from || failed.count < MAX_FAILED_STARTS;
344
- }
345
-
346
- /**
347
- * Record whether a failed run died before it performed sustained work.
348
- *
349
- * @param {string} address
350
- * @param {number} from
351
- * @param {number} livedMs
352
- * @returns {{ at: number, count: number, blocked: boolean, limit: number, fastMs: number }}
353
- */
354
- noteStartFailure(address, from, livedMs) {
355
- if (!(livedMs < START_FAST_FAIL_MS)) {
356
- this.#failedStarts.delete(address);
357
- return { at: -1, count: 0, blocked: false, limit: MAX_FAILED_STARTS, fastMs: START_FAST_FAIL_MS };
358
- }
359
- const previous = this.#failedStarts.get(address);
360
- const next = {
361
- at: from,
362
- count: previous?.at === from ? previous.count + 1 : 1
363
- };
364
- this.#failedStarts.set(address, next);
365
- return {
366
- ...next,
367
- blocked: next.count >= MAX_FAILED_STARTS,
368
- limit: MAX_FAILED_STARTS,
369
- fastMs: START_FAST_FAIL_MS
370
- };
371
- }
372
-
373
- /**
374
- * An output that no longer exists and has no run left on it.
375
- *
376
- * How its last run ended, what went wrong and which position kept failing are
377
- * facts about THAT output. The name follows from the key, so the next output
378
- * with the same parameters has the same address; kept, those facts would
379
- * greet it as its own — a failed ending makes its first wait throw before any
380
- * encoder is placed, and nothing would ever clear it.
381
- *
382
- * @param {string} address
383
- */
384
- forgetOutput(address) {
385
- if (this.runsOn(address).length > 0) {
386
- return;
387
- }
388
- this.#lastState.delete(address);
389
- this.#lastError.delete(address);
390
- this.#lastProgress.delete(address);
391
- this.#failedStarts.delete(address);
392
- }
393
-
394
- /** @param {string} address @returns {{ at: number, count: number, blocked: boolean, limit: number }} */
395
- startFailureOf(address) {
396
- const failure = this.#failedStarts.get(address) ?? { at: -1, count: 0 };
397
- return { ...failure, blocked: failure.count >= MAX_FAILED_STARTS, limit: MAX_FAILED_STARTS };
398
- }
399
-
400
- /**
401
- * What the map says about one segment of one output, and about the map it
402
- * sits in.
403
- *
404
- * Asked by whoever is holding a request and measuring the wait: a wait means
405
- * one thing at the top rank and another at the bottom, and telling them apart
406
- * needs both the segment's own rank and the highest rank stated, since a rank
407
- * is a position in this map and not an absolute number.
408
- *
409
- * AND AN EMPTY MAP IS NOT AN ANSWER. A top rank of zero says the map has not
410
- * been built yet — a session created a moment ago, before the first pass —
411
- * and that is a different thing from "nobody is coming". Conflated, every
412
- * request behind the run reads as absent for as long as a fresh session has
413
- * no map.
414
- *
415
- * It exists because the one caller reached through this object into the store
416
- * behind it. A reach like that is how a store becomes the surface: the day it
417
- * changes, a caller two layers away breaks for a reason it cannot see.
418
- *
419
- * @param {string} address
420
- * @param {number} index
421
- * @returns {{ rank: number, topRank: number }}
422
- */
423
- rankAt(address, index) {
424
- return this.#demand.rankOf(address, index);
425
- }
426
-
427
- /**
428
- * How many encoder processes are running on this machine right now, over
429
- * every output.
430
- *
431
- * ONE COUNT, and it is this class's because this class is what makes and
432
- * unmakes runs: adopted the moment one exists and forgotten the moment one
433
- * ends, both synchronously. The session manager answered the same question
434
- * twice by walking its own registry — once per SESSION and once per RUN —
435
- * which agreed only while a session held at most one run. It has held several
436
- * since the plan was allowed to place them, and the per-session count is the
437
- * wrong one of the two wherever they differ: what a second encoder costs was
438
- * measured between ffmpeg PROCESSES, not between outputs.
439
- *
440
- * A SUSPENDED run is not counted. It is stopped where it stands and is using
441
- * nothing; a cost measured beside it is a cost measured alone.
442
- *
443
- * @returns {number}
444
- */
445
- /**
446
- * How many encoders are alive on each output, suspended ones included.
447
- *
448
- * What the machine-wide admission counts as holding a place. A suspended
449
- * encoder is counted here, unlike in {@link runningCount}: that one answers
450
- * what is competing for the processor this instant, this one what the
451
- * machine is committed to — and a parked encoder resumes the moment the
452
- * viewer catches up.
453
- *
454
- * @returns {Map<string, number>}
455
- */
456
- liveRunsByAddress() {
457
- /** @type {Map<string, number>} */
458
- const byAddress = new Map();
459
- for (const [address, runs] of this.#runs) {
460
- const alive = runs.filter((run) => run.isAlive).length;
461
- if (alive > 0) {
462
- byAddress.set(address, alive);
463
- }
464
- }
465
- return byAddress;
466
- }
467
-
468
- runningCount() {
469
- let running = 0;
470
- for (const runs of this.#runs.values()) {
471
- for (const run of runs) {
472
- if (run.isAlive && !run.isSuspended) {
473
- running += 1;
474
- }
475
- }
476
- }
477
- return running;
478
- }
479
-
480
- /**
481
- * How long an output is, once its playlist is known.
482
- *
483
- * @param {string} address
484
- * @param {number} segmentCount
485
- */
486
- setSegmentCount(address, segmentCount) {
487
- this.coverageOf(address).setSegmentCount(segmentCount);
488
- }
489
-
490
- /**
491
- * Segments that already exist — from a previous life of this process, or
492
- * because somebody else made them. Told to the map, which is what stops an
493
- * encoder being started to make them again.
494
- *
495
- * @param {string} address
496
- * @param {Iterable<number>} indexes
497
- */
498
- noteAlreadyMade(address, indexes) {
499
- for (const index of indexes) {
500
- this.noteProduced(address, index);
501
- }
502
- }
503
-
504
- /**
505
- * A viewer states what it is waiting for. Replaces whatever it said before.
506
- *
507
- * @param {object} params
508
- * @param {string} params.claimant
509
- * @param {string} params.address
510
- * @param {number} params.from
511
- * @param {number} params.to
512
- * @param {number} [params.priority] - Higher is sooner. One viewer states
513
- * several stretches at once — what must be ready before they set off, what
514
- * is reachable while they watch it, the rest of the track — and the filling
515
- * takes them in this order. Absent means one undifferentiated want, which
516
- * is what a caller that knows only a position states.
517
- */
518
- /**
519
- * What is wanted of one output, in its own segment numbers.
520
- *
521
- * ONE MAP, ALREADY MERGED, AND WITH NOBODY'S NAME ON IT. It is built once per
522
- * film by the layer that knows where the viewers are; this layer receives it
523
- * converted into an output's own numbering and never asks who is in it.
524
- *
525
- * That replaced a window per viewer per band stated here and merged here,
526
- * which was the same work done twice in two layers, with the viewer's name as
527
- * the key of a claim — against the rule that the encoding and the viewer are
528
- * not connected at all.
529
- *
530
- * An empty map says nobody is coming anywhere in this output, and the plan
531
- * stops its encoders for it. Nothing has to be released when somebody leaves:
532
- * the map that arrives next simply does not have them in it.
533
- *
534
- * @param {string} address
535
- * @param {{ from: number, to: number, priority: number, withinSeconds: number }[]} zones
536
- */
537
- notePriorityMap(address, zones) {
538
- this.#demand.state(address, zones);
539
- // NOBODY IS COMING HERE, so what was remembered about this output's input
540
- // is about nobody. Kept, those three entries would stay for the life of the
541
- // process, and the wait they describe would greet whoever opens this output
542
- // next — a viewer arriving is new information, and one attempt for them is
543
- // right whatever the last one met.
544
- if (!Array.isArray(zones) || zones.length === 0) {
545
- this.#forgetInputState(address);
546
- }
547
- }
548
-
549
- /**
550
- * A segment has been finished, by whichever run made it.
551
- *
552
- * @param {string} address
553
- * @param {number} index
554
- */
555
- noteProduced(address, index) {
556
- // Nothing is told to the store: by the time this is called the piece is
557
- // ALREADY under its served name, because the rename is what closing it
558
- // means. A statement kept beside the disk would be a second owner of one
559
- // fact, which removed the stale second owner from the coverage map.
560
- this.coverageOf(address).markReady(index);
561
- this.#segmentCoverage?.announce?.(address, index);
562
- for (const run of this.runsOn(address)) {
563
- run.noteProduced(index);
564
- }
565
- }
566
-
567
- /**
568
- * Decide and act, for every output anybody wants anything of and every output
569
- * that still has an encoder on it.
570
- *
571
- * Safe to call as often as anything changes: the plan is a function of the
572
- * state, so a pass that finds nothing to change does nothing.
573
- */
574
- reconcile() {
575
- const addresses = new Set([...this.#demand.addresses(), ...this.#runs.keys()]);
576
- for (const address of addresses) {
577
- this.#reconcileOne(address);
578
- }
579
- // WHAT THIS CLASS BELIEVES, said by this class. `describe()` was written
580
- // and called from nowhere, so on 2026-09-05 the question "why did the plan
581
- // not see the gap the viewer was stopped at" had to be answered by
582
- // inference from start and stop lines, and was not answered at all.
583
- //
584
- // Printed on CHANGE rather than on a timer: a quiet session says nothing, a
585
- // session that is deciding something says what it decided, and there is no
586
- // interval to choose.
587
- const state = this.describe();
588
- if (state !== this.#lastDescribed) {
589
- this.#lastDescribed = state;
590
- this.logger.info(state);
591
- }
592
- }
593
-
594
- /**
595
- * @param {string} address
596
- */
597
- #reconcileOne(address) {
598
- // WHAT EXISTS IS ASKED OF THE DISK, HERE, EVERY TIME. The plan is arithmetic
599
- // over what is made, what is being made and what is wanted, and the first of
600
- // those is not this layer's to remember.
601
- const coverage = this.#upToDateCoverage(address);
602
- // A run that has ended and said nothing. One built here reports its own
603
- // ending and is released by `noteEnded`; one ADOPTED from elsewhere — a
604
- // session whose encoder stopped — has no such promise, and its claim would
605
- // otherwise sit in the map for the life of the process, telling the plan
606
- // that a stretch nobody is making is being made. Nothing would ever be
607
- // started there again.
608
- for (const run of this.runsOn(address)) {
609
- if (!run.isAlive && !run.isStopping) {
610
- this.noteEnded({
611
- address,
612
- run,
613
- ending: ENCODE_EXIT.GONE,
614
- because: "it is no longer running, and it did not say so"
615
- });
616
- }
617
- }
618
- // ITS INPUT WAS NOT THERE A MOMENT AGO, so nothing is placed yet. The sweep
619
- // above still runs — a claim left by a dead run must be released whatever
620
- // the reason — and only the placing waits. This is the one thing that makes
621
- // the delay bind: it used to be timed against the dead run, which the plan
622
- // does not consult, so a fresh run went to the same place as fast as ffmpeg
623
- // could fail there.
624
- //
625
- // AND ONLY WHILE NOTHING IS PRODUCING THERE. A run still alive on this
626
- // output is proof the input can be read, whatever a run beside it met, so
627
- // the wait must not silence an output that is working.
628
- if (this.#isQuiet(address) && this.runsOn(address).every((run) => !run.isAlive)) {
629
- return;
630
- }
631
- // ONE MAP, NOT ONE WINDOW PER VIEWER PER ZONE.
632
- //
633
- // Two viewers a few seconds apart state stretches that overlap, and the plan
634
- // puts one encoder on each stretch it is given — so unmerged windows buy an
635
- // encoder per viewer for film they both want, which is the opposite of what
636
- // sharing the output is for. Merged, the highest rank and the soonest time
637
- // per number win and the stretches do not overlap, so one encoder serves
638
- // everyone standing in front of it.
639
- //
640
- // Asked of the register, which is the thing that holds the windows. This
641
- // used to reach into the layer that STATES them for the same arithmetic,
642
- // which is the coupling the layer rule forbids; the arithmetic itself now
643
- // lives where it belongs to nobody.
644
- const windows = this.#demand.mapOn(address);
645
- const live = this.runsOn(address).filter((run) => run.isAlive);
646
- // Asked ONCE. It is arithmetic over measurements, but it also says out loud
647
- // when the reason it cuts the budget changes, so asking it three times in
648
- // one pass is three chances to say a thing that happened once.
649
- const maxRuns = this.#withinMachine(address, live, this.#affordableOn(address, live));
650
- // THE TERMS EVERY ARRIVAL IS COMPUTED FROM, named here so the line below can
651
- // print them. A decision of this plan is `delay + (index - at) / rate +
652
- // madeBetween * refetch` against a deadline, so without the rate and the two
653
- // prices no recorded decision can be reproduced — which is what happened
654
- // with the one-piece intervals of 2026-09-08: the rate was substituted six
655
- // times from the speeds the session reported elsewhere and none of them gave
656
- // the answer the plan had given.
657
- const costs = this.#costs.seconds();
658
- const refetchSecPerFilmSecond = this.refetchSecPerFilmSecond(address);
659
- const speedX = this.#speedOn(address, live);
660
- const actions = planEncoders({
661
- coverage,
662
- windows,
663
- // The runs themselves. The plan is arithmetic and reads four numbers off
664
- // each; what it hands back names the run by BEING it, so nothing has to
665
- // invent a token to refer to one by.
666
- runs: live,
667
- maxRuns,
668
- segmentSeconds: this.segmentSeconds,
669
- // What a start and a kill cost, measured from this host's own runs rather
670
- // than written into the code from one machine's reading. Zero until
671
- // something has been measured, which is the same convention as the
672
- // refetch price and is stated so the bias is known.
673
- ...costs,
674
- // What a second of film costs to fetch again, in seconds of swarm time.
675
- // Answered by whoever measures the film's own byte rate and the swarm's;
676
- // zero until they have, which makes driving through look cheaper than it
677
- // is and is stated here so the bias is known.
678
- refetchSecPerFilmSecond,
679
- // How much slower one encoder runs beside others, read off this host's own
680
- // startup measurement. A pure function over a measured table: beyond what
681
- // was measured it holds the largest reading rather than continuing a curve
682
- // nothing observed.
683
- contentionPenaltyFor: (others) => contentionPenalty(others, this.contentionPenalties).penalty,
684
- speedX
685
- });
686
-
687
- // A move is the plan taking a running encoder away from where it already
688
- // stands, which is exactly the decision that was found wandering back and
689
- // forth in the field on 2026-09-07 with no way to see why: the "because"
690
- // line names the comparison in words, never the numbers it was decided
691
- // from. Said here, once per reconcile, and only when a move actually
692
- // happens — everything a rerun of the same decision needs: the windows
693
- // this call saw (priority, the real time, which side of the viewers),
694
- // the budget, and where every live run stood.
695
- // WHAT WAS DECIDED AND WITH WHAT INTERVAL, said whenever anything is placed
696
- // or taken away — not only on a move.
697
- //
698
- // Field 2026-09-08 could not be diagnosed from this line: it printed the
699
- // windows, the budget and where the live runs stood, and NOT the intervals
700
- // the actions carried. What the session actually did was give every encoder
701
- // an interval of exactly ONE segment — 63 runs, each making one piece and
702
- // exiting, twelve of them normally — and the reasons printed beside them
703
- // read as moves, so the fault was diagnosed three times as something it was
704
- // not. An interval is what a run is, and it was the one thing missing.
705
- //
706
- // AND THE TERMS, for the same reason one step further: an interval says what
707
- // was decided and the terms say why. `speed` is what every arrival is
708
- // divided by, so a decision recorded without it can be re-read and not
709
- // recomputed; `firstByte` and `kill` are what a start and a stop cost here;
710
- // `refetch` is what a second of film costs to fetch again. A zero in the
711
- // last three is a measurement nobody has taken, not a free operation, and it
712
- // is printed so that reading it as free is a choice rather than an accident.
713
- if (actions.some((action) => action.type !== "keep")) {
714
- this.logger.info(
715
- `encode-plan on ${address}: ` +
716
- `${actions.map((action) => `${action.type} #${action.from ?? "?"}..#${action.to ?? "?"}`).join(", ")}` +
717
- ` [speed=${speedX.toFixed(2)}x firstByte=${costs.firstByteWaitSec.toFixed(2)}s ` +
718
- `kill=${costs.killCostSec.toFixed(2)}s refetch=${refetchSecPerFilmSecond.toFixed(3)}s/s ` +
719
- `maxRuns=${maxRuns} live=${live.length}]`
720
- );
721
- }
722
- if (actions.some((action) => action.type === "move")) {
723
- this.logger.info(
724
- `encode-plan move on ${address}: windows=${JSON.stringify(windows)} ` +
725
- `maxRuns=${maxRuns} ` +
726
- `live=${JSON.stringify(live.map((run) => ({ from: run.from, to: run.to, head: run.head, speedX: run.speedX })))}`
727
- );
728
- }
729
- for (const action of actions) {
730
- if (action.type === "stop") {
731
- this.#stop(action.run, action.because);
732
- continue;
733
- }
734
- if (action.type === "move") {
735
- // A running encoder's position cannot be changed — it is fixed when the
736
- // process starts — so a move is this one ending and another beginning
737
- // where the material is missing. Both halves are recorded as what they
738
- // are, which is why the ending of a moved run is not called normal.
739
- this.#stop(action.run, action.because);
740
- this.#start(address, action.from, action.to, action.because);
741
- continue;
742
- }
743
- if (action.type === "start") {
744
- this.#start(address, action.from, action.to, action.because);
745
- continue;
746
- }
747
- // A run that stays keeps its claim current: the free stretch ahead of it
748
- // may have shrunk since it was given one.
749
- //
750
- // THE CLAIM IS THE STRETCH IT WAS GIVEN, and there is one rule for that
751
- // everywhere. It used to be narrowed here to what the run had already
752
- // MADE whenever the run had no end, which meant a run claimed the single
753
- // number it was writing and nothing beyond. The plan then read the road
754
- // in front of a working encoder as free and started more encoders on it:
755
- // three processes writing one directory with the same names, field
756
- // 2026-09-06, and a piece of the film lost for good when the first of
757
- // them was cleaned up after.
758
- //
759
- // The worry that narrowing was written for is real and is answered where
760
- // it belongs — a viewer opening the same film further in must not find
761
- // every number taken. That is the plan's business, and the plan can take
762
- // road away from a run that has no end, because such a run carries no
763
- // `-to` and simply stops when its head meets somebody else's claim.
764
- coverage.claim(action.run, action.from, endOfRun({ from: action.from, to: action.to }));
765
- }
766
-
767
- // NOBODY IS MAKING WHAT SOMEBODY IS WAITING FOR. Said here, with the numbers
768
- // the decision was taken from, because it is the one state in which a viewer
769
- // waits for ever and every line above it reads as a healthy proxy.
770
- //
771
- // Field 2026-09-07, twice in one evening: the last word about an output was
772
- // "the film is no worse off without it", and after it nothing — no run, no
773
- // refusal, no answer to the browser's request for the header. The wait ended
774
- // at the browser's own timeout with a message naming no cause, and the
775
- // proxy's log named none either.
776
- //
777
- // SAID ONCE PER STATE, not once per pass. A stuck output is reconciled on
778
- // every event that touches it, and a line repeated for as long as the state
779
- // lasts is what buried the last one: 49 295 copies of `send queue stuck` in
780
- // a 159 090-line file, 31 % of the log, all of one wedge.
781
- const wanting = firstUnmetWant(coverage, windows);
782
- const stillRunning = this.runsOn(address).filter((run) => run.isAlive);
783
- if (wanting === null || stillRunning.length > 0) {
784
- this.#lastUnmet.delete(address);
785
- } else if (this.#lastUnmet.get(address) !== wanting) {
786
- this.#lastUnmet.set(address, wanting);
787
- const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
788
- this.logger.warn(
789
- `encode: #${wanting} of ${address} is wanted and NO ENCODER IS MAKING IT — ` +
790
- `ready=${coverage.stats().ready} of ${coverage.segmentCount} ` +
791
- `files=${held < 0 ? "?" : held} maxRuns=${maxRuns} ` +
792
- `windows=${JSON.stringify(windows)}`
793
- );
794
- }
795
- }
796
-
797
- /**
798
- * @param {string} address
799
- * @param {number} from
800
- * @param {number} to
801
- * @param {string} because
802
- */
803
- #start(address, from, to, because) {
804
- // The encoder is built here and now: whoever builds one waits for nothing,
805
- // so it exists by the time this line returns. That is what makes the
806
- // stretch held from this instant — this class knows what it is making
807
- // because it has just made it, and no second encoder can be started for the
808
- // same stretch on the next pass.
809
- //
810
- // It was not always so. The builder used to answer with nothing and start
811
- // the encoder behind the answer, so the stretch stayed FREE for as long as
812
- // that took, and every pass in between started another one: 684 starts in
813
- // 482 seconds of field 2026-09-05, of which 973 answers said the encoder
814
- // was not there yet — every start without exception.
815
- //
816
- // The run names itself: identity is a property of the thing, and two
817
- // places minting names is how one stops being unique.
818
- const run = this.makeRun({ address, from, to, because });
819
- if (!run) {
820
- // A refusal, not a wait: no session serves this output, or this position
821
- // has failed to start too many times running.
822
- this.logger.warn(`encode: no encoder could be made for #${from}..#${to} of ${address}`);
823
- return;
824
- }
825
- const onThisOutput = this.#runs.get(address) ?? [];
826
- onThisOutput.push(run);
827
- this.#runs.set(address, onThisOutput);
828
- // Nothing has to be un-proved when a run takes a stretch that has already
829
- // been written. A piece is only ever NAMED as served once it is closed, and
830
- // a run writing that number again writes under a working name until it
831
- // closes its own — so the file standing there is a complete piece made by
832
- // somebody, and serving it is right until the newer one replaces it whole.
833
- // The claim comes after the run exists, and that is not a race: everything
834
- // between is synchronous, and a process cannot say a word before the next
835
- // tick. What it removes is the second act — building a run and starting it
836
- // were two steps, and two owners each performed the second one.
837
- this.coverageOf(address).claim(run, from, endOfRun({ from, to }));
838
- }
839
-
840
- /**
841
- * The best figure this host has for one encoder on this output: the
842
- * processing speed a run here has measured (`EncodeRun.speedX`), or what this
843
- * output was last measured doing and the startup measurements predict
844
- * (`startingSpeedFor`), which exists before any run has closed two pieces and
845
- * after a restart. The run owns its speed; nothing here keeps a copy.
846
- *
847
- * It is the MACHINE's speed: input waits for the swarm are not in it. What
848
- * the swarm delivers is the separate supply term
849
- * (`refetchSecPerFilmSecond`).
850
- *
851
- * @param {string} address
852
- * @param {{ speedX: number }[]} live
853
- * @returns {number}
854
- */
855
- #speedOn(address, live) {
856
- return Math.max(
857
- live.reduce((best, run) => Math.max(best, run.speedX || 0), 0),
858
- this.startingSpeedFor(address) || 0
859
- );
860
- }
861
-
862
- /**
863
- * How many encoders may run on this output, from every limit at once.
864
- *
865
- * The processor is one of them and is answered from outside, where the
866
- * machine is measured. The other two are known here: what the swarm delivers,
867
- * through the seconds of swarm time a second of film costs, and — once it is
868
- * supplied — the memory the piece store may hold against what one encoder's
869
- * reader keeps.
870
- *
871
- * Said out loud when it is not the processor that decided, because "why is
872
- * there only one encoder" is otherwise a question no log can answer.
873
- *
874
- * @param {string} address
875
- * @param {{ speedX: number }[]} live
876
- * @returns {number}
877
- */
878
- #affordableOn(address, live) {
879
- const byProcessor = Math.max(0, this.maxRunsFor(address));
880
- const fastest = this.#speedOn(address, live);
881
- const budget = affordableRuns({
882
- byProcessor,
883
- speedX: fastest,
884
- refetchSecPerFilmSecond: this.refetchSecPerFilmSecond(address),
885
- // How much slower one encoder runs beside others, read off this host's own
886
- // startup measurement. A pure function over a measured table: beyond what
887
- // was measured it holds the largest reading rather than continuing a curve
888
- // nothing observed.
889
- contentionPenaltyFor: (others) => contentionPenalty(others, this.contentionPenalties).penalty
890
- });
891
- if (budget.runs !== byProcessor && budget.because !== this.#lastBudgetReason.get(address)) {
892
- this.#lastBudgetReason.set(address, budget.because);
893
- this.logger.info(
894
- `encode: ${budget.runs} encoder(s) on ${address.slice(0, 60)} — ${budget.because} ` +
895
- `(the processor alone would allow ${byProcessor})`
896
- );
897
- }
898
- return budget.runs;
899
- }
900
-
901
- /**
902
- * The per-output limit, bounded by what the whole machine can still hold.
903
- *
904
- * The per-output answer is at least one whatever else is running; the
905
- * machine's may be none, and that is the refusal: the output gets no encoder
906
- * until one elsewhere ends. It is never below what already runs here, so a
907
- * refusal stops a start and never takes an encoder away.
908
- *
909
- * Said out loud when the machine is what bound it, once per change.
910
- *
911
- * @param {string} address
912
- * @param {object[]} live
913
- * @param {number} perOutput
914
- * @returns {number}
915
- */
916
- #withinMachine(address, live, perOutput) {
917
- if (!this.admission) {
918
- return perOutput;
919
- }
920
- const machine = this.admission.placesFor(address, live.length);
921
- const runs = Math.min(perOutput, machine.runs);
922
- const said = runs < perOutput ? `${runs}:${machine.because}` : "";
923
- if (said !== (this.#lastMachineBound.get(address) ?? "")) {
924
- if (said) {
925
- this.logger.info(
926
- `encode: ${runs} encoder(s) on ${address} — the whole machine holds no more ` +
927
- `(${machine.because}; this output alone would be allowed ${perOutput})`
928
- );
929
- this.#lastMachineBound.set(address, said);
930
- } else {
931
- this.#lastMachineBound.delete(address);
932
- }
933
- }
934
- return runs;
935
- }
936
-
937
- /**
938
- * Take charge of a run this class did not start.
939
- *
940
- * The browser asks for a stream and a run begins for it, long before this
941
- * class has an opinion. Left unknown, that run would be invisible to the plan
942
- * — which would then start a second encoder over the same numbers, believing
943
- * nothing was being made there. So whoever starts one hands it over, and from
944
- * then on it is planned like any other.
945
- *
946
- * @param {string} address
947
- * @param {{ id: string, from: number, to: number, head: number, speedX: number, isAlive: boolean, stop: (because: string) => void }} run
948
- */
949
- adopt(address, run) {
950
- if (!run) {
951
- return;
952
- }
953
- const onThisOutput = this.#runs.get(address) ?? [];
954
- if (onThisOutput.includes(run)) {
955
- return;
956
- }
957
- onThisOutput.push(run);
958
- this.#runs.set(address, onThisOutput);
959
- this.coverageOf(address).claim(run, run.from, endOfRun(run));
960
- }
961
-
962
- /**
963
- * @param {object} run
964
- * @param {string} because
965
- */
966
- #stop(run, because) {
967
- run.stop(because);
968
- }
969
-
970
- /**
971
- * A run has ended, however it ended. Its stretch goes back to the map — what
972
- * it finished stays made — and the ending is counted.
973
- *
974
- * Wired by whoever builds the run, so that a run built outside this class is
975
- * still accounted for.
976
- *
977
- * @param {import("../encode/EncodeRun.js").RunEnded} ended
978
- */
979
- noteEnded(ended) {
980
- this.#lastState.set(ended.address, ended.run?.state ?? "IDLE");
981
- if (ended.lastError) {
982
- this.#lastError.set(ended.address, ended.lastError);
983
- } else if (ended.because && ended.ending !== ENCODE_EXIT.COMPLETE) {
984
- this.#lastError.set(ended.address, ended.because);
985
- }
986
- const progress = ended.run?.progress?.snapshot?.();
987
- if (progress) {
988
- this.#lastProgress.set(ended.address, progress);
989
- }
990
- this.#costs.note(ended);
991
- // Exactly one ending is normal — the run reached the end of the stretch it
992
- // was given and closed its last file. Every other leaves a piece open, and
993
- // that piece is under this run's OWN working name, so clearing up after it
994
- // is a name match: no stretch to search and no bytes to judge. Done for
995
- // every ending, the normal one included, since a run that finished cleanly
996
- // has nothing under a working name and the sweep then removes nothing.
997
- this.#segmentCoverage?.clearUpAfter(ended.address, ended.from);
998
- this.coverageOf(ended.address).release(ended.run);
999
- const remaining = this.runsOn(ended.address).filter((run) => run !== ended.run);
1000
- if (remaining.length === 0) {
1001
- this.#runs.delete(ended.address);
1002
- } else {
1003
- this.#runs.set(ended.address, remaining);
1004
- }
1005
- this.#endings.set(ended.ending, (this.#endings.get(ended.ending) ?? 0) + 1);
1006
- this.#noteInputAvailability(ended);
1007
- }
1008
-
1009
- /**
1010
- * Remember, per output, that its input was not there — and until when nothing
1011
- * is to be placed on it.
1012
- *
1013
- * **Why the plan has to hold this.** A run whose input has gone is not alive,
1014
- * so the plan sees the stretch it held as free and places another run there at
1015
- * once — and the next one dies the same way, because nothing about the state
1016
- * has changed. There WAS a delay for exactly this, doubling from 2 s to 15 s,
1017
- * and it governed only the dead run's own retry while the plan went on placing
1018
- * fresh ones beside it. The comment beside that timer predicted this in as
1019
- * many words and the code did not prevent it. Field 2026-09-12: 2432 ffmpeg
1020
- * starts in 23 minutes, one every 0.57 s, for 61 minutes, against a delay that
1021
- * had long since reached its 15 s cap.
1022
- *
1023
- * So the delay lives where the decision is taken. It is not a cure for the
1024
- * input being away — that is the store's claim being withdrawn and the piece
1025
- * being fetched again — it is what stops one absent input from costing a
1026
- * thousand processes and a quarter of a million log lines while it is away.
1027
- *
1028
- * @param {{ address: string, ending: string }} ended
1029
- * @returns {void}
1030
- */
1031
- #noteInputAvailability(ended) {
1032
- if (ended.ending !== ENCODE_EXIT.INPUT_LOST) {
1033
- // CLEARED ONLY BY PROOF THAT THE INPUT WAS THERE, which is a segment
1034
- // having come out of it. Any other ending was nearly the rule here and is
1035
- // wrong: at the moment of failure several runs end at once, and one of
1036
- // them ending `gone` or `stopped` without producing a thing says nothing
1037
- // about the input — it would have lifted the wait the one beside it had
1038
- // just set, which is the storm again with an extra step.
1039
- const produced =
1040
- ended.firstOutputMs !== null && ended.firstOutputMs !== undefined
1041
- ? true
1042
- : Number.isFinite(ended.reached) && Number.isFinite(ended.from) && ended.reached >= ended.from;
1043
- if (produced) {
1044
- this.#inputLostAttempts.delete(ended.address);
1045
- this.#quietUntil.delete(ended.address);
1046
- }
1047
- return;
1048
- }
1049
- const attempts = (this.#inputLostAttempts.get(ended.address) ?? 0) + 1;
1050
- this.#inputLostAttempts.set(ended.address, attempts);
1051
- const delayMs = Math.min(
1052
- INPUT_QUIET_MAX_MS,
1053
- INPUT_QUIET_BASE_MS * 2 ** Math.min(attempts - 1, 6)
1054
- );
1055
- this.#quietUntil.set(ended.address, this.now() + delayMs);
1056
- this.logger.info(
1057
- `encode-plan on ${ended.address}: its input was not there (attempt ${attempts}) — ` +
1058
- `placing nothing for ${Math.round(delayMs / 1000)}s`
1059
- );
1060
- // THE WAKE-UP, because a plan that refuses to act needs something to ask it
1061
- // again: nothing about the state changes while the data is away, so no event
1062
- // would arrive to reconsider it.
1063
- const timer = setTimeout(() => {
1064
- this.#quietTimers.delete(ended.address);
1065
- this.planSoon();
1066
- }, delayMs);
1067
- timer.unref?.();
1068
- const previous = this.#quietTimers.get(ended.address);
1069
- if (previous) {
1070
- clearTimeout(previous);
1071
- }
1072
- this.#quietTimers.set(ended.address, timer);
1073
- }
1074
-
1075
- /**
1076
- * Whether this output is still waiting before anything may be placed on it.
1077
- *
1078
- * A boolean rather than the milliseconds left: the figure had one reader and
1079
- * that reader only asked whether it was above zero, so it was a number
1080
- * computed and thrown away. How long the wait is was said when it began.
1081
- *
1082
- * @param {string} address
1083
- * @returns {boolean}
1084
- */
1085
- #isQuiet(address) {
1086
- const until = this.#quietUntil.get(address);
1087
- if (!Number.isFinite(until)) {
1088
- return false;
1089
- }
1090
- if (until - this.now() <= 0) {
1091
- this.#quietUntil.delete(address);
1092
- return false;
1093
- }
1094
- return true;
1095
- }
1096
-
1097
- /**
1098
- * Forget everything remembered about an output nobody is producing for.
1099
- *
1100
- * Three maps are keyed by address, and an output that goes away leaves an
1101
- * entry in each for the life of the process. Small, and exactly the shape of
1102
- * accumulation this layer was built to remove from the session.
1103
- *
1104
- * @param {string} address
1105
- * @returns {void}
1106
- */
1107
- #forgetInputState(address) {
1108
- this.#inputLostAttempts.delete(address);
1109
- this.#quietUntil.delete(address);
1110
- const timer = this.#quietTimers.get(address);
1111
- if (timer) {
1112
- clearTimeout(timer);
1113
- this.#quietTimers.delete(address);
1114
- }
1115
- }
1116
-
1117
- /**
1118
- * How runs have ended over the life of this process, by cause.
1119
- *
1120
- * The abnormal classes are meant to stand at zero. Without the count,
1121
- * "we understand why it ended" is indistinguishable from "we noticed it once".
1122
- *
1123
- * @returns {Record<string, number>}
1124
- */
1125
- endings() {
1126
- /** @type {Record<string, number>} */
1127
- const tally = {};
1128
- for (const ending of Object.values(ENCODE_EXIT)) {
1129
- tally[ending] = this.#endings.get(ending) ?? 0;
1130
- }
1131
- return tally;
1132
- }
1133
-
1134
- /**
1135
- * One line saying what this proxy is encoding and whether anybody is waiting.
1136
- *
1137
- * `waiting` is the point of it: a proxy with encoders running and a viewer
1138
- * still stopped at a segment nobody is making is the failure this layer was
1139
- * built to remove, and it is visible here rather than inferred from a log.
1140
- *
1141
- * @returns {string}
1142
- */
1143
- describe() {
1144
- const parts = [];
1145
- for (const address of new Set([...this.#demand.addresses(), ...this.#runs.keys()])) {
1146
- const coverage = this.coverageOf(address);
1147
- const stated = this.#demand.mapOn(address);
1148
- const windows = stated.map((zone) => ({ from: zone.from, to: zone.to }));
1149
- const waiting = firstUnmetWant(coverage, windows);
1150
- const runs = this.runsOn(address)
1151
- .map((run) => `#${run.head}..#${run.to}@${run.speedX.toFixed(1)}x`)
1152
- .join(" ");
1153
- // The zones as they were stated, with their order, so a plan that is
1154
- // working at the wrong end of the film is visible rather than inferred.
1155
- const zones = [...stated]
1156
- .sort((left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from)
1157
- .map((w) => `p${w.priority ?? 0}:#${w.from}..#${w.to}`)
1158
- .join(" ");
1159
- // THE WHOLE ADDRESS. Cut to sixty characters, every output of one film
1160
- // printed the same string — the picture, its quality steps and each
1161
- // soundtrack are told apart only by the tail — so three lines of this
1162
- // could not be matched to the three things they describe. Read on
1163
- // 2026-09-07 while accounting for a session that produced nothing, and
1164
- // the accounting had to be done by which line carried a run.
1165
- //
1166
- // And WHAT THE DISK HOLDS beside what is proven closed. They are two
1167
- // different statements: files with nothing proving them closed reads as a
1168
- // reporting fault, no files at all reads as an output yet to be made, and
1169
- // the difference decides where to look.
1170
- const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
1171
- // AND WHETHER THE MAP IS BEING SERVED IN ITS OWN ORDER. The zones say
1172
- // what matters most; this says what the viewer actually waited for, by
1173
- // band. Waits at `now` are the ones that cost a spinner, and until this
1174
- // existed there was no figure anywhere saying whether the urgent zone was
1175
- // served first — the map could have been read backwards and every line
1176
- // above would have looked the same.
1177
- const served = this.#describeWaits(address);
1178
- parts.push(
1179
- `${address} ready=${coverage.stats().ready}` +
1180
- `${held < 0 ? "" : ` of ${held} file(s) on disk`} ` +
1181
- `zones=[${zones}] runs=[${runs}] ` +
1182
- `waiting=${waiting === null ? "nobody" : `#${waiting}`}` +
1183
- `${served ? ` served[${served}]` : ""}`
1184
- );
1185
- }
1186
- const tally = this.endings();
1187
- const endings = Object.entries(tally)
1188
- .map(([cause, count]) => `${cause}=${count}`)
1189
- .join(" ");
1190
- return `encode: ${parts.length === 0 ? "nothing wanted" : parts.join(" | ")} :: endings ${endings}`;
1191
- }
1192
- }
1
+ /**
2
+ * @file How many encoders run on this proxy, on which outputs, and over which
3
+ * stretches.
4
+ *
5
+ * The application layer over `encode/`. It holds four things and owns none of
6
+ * their rules:
7
+ *
8
+ * 1. what viewers want (`SegmentDemand`), stated once each and read as a union;
9
+ * 2. what has been made and what is being made, one `CoverageMap` per output;
10
+ * 3. the encoders that are running (`EncodeRun`), each over a stretch;
11
+ * 4. a tally of how every run ended, which is what makes "abnormal endings do
12
+ * not happen" a number rather than an impression.
13
+ *
14
+ * The decision itself is `EncodePlan.planEncoders`, from numbers alone. This
15
+ * carries it out, and everything it cannot know is injected: how many encoders
16
+ * this machine can afford, how a run is built for a given stretch, and which
17
+ * segments already exist.
18
+ *
19
+ * **No viewer reaches the decision.** A viewer states a window and is forgotten
20
+ * as a name; what the plan sees is a union of windows. That is the rule the
21
+ * layer exists for, stated by the user 2026-09-04: requests come from any
22
+ * viewers in any number, encoders are managed to suit them, and viewers get the
23
+ * result when it is ready.
24
+ */
25
+
26
+ import { CoverageMap } from "./CoverageMap.js";
27
+ import { firstUnmetWant, planEncoders } from "./EncodePlan.js";
28
+ import { endOfRun } from "./EncodeRun.js";
29
+ import { ENCODE_EXIT } from "./encode-exit.js";
30
+ import { affordableRuns } from "./run-budget.js";
31
+ import { RunCosts } from "./run-costs.js";
32
+ import { contentionPenalty } from "./contention.js";
33
+ import { SegmentDemand } from "./SegmentDemand.js";
34
+ import { runStateOf } from "./encode-run-state.js";
35
+
36
+ /**
37
+ * @typedef {Object} SegmentCoverage
38
+ * @property {(address: string) => number[]} provenNumbers
39
+ * @property {(address: string, index: number) => void} announce
40
+ * @property {(address: string) => number} filesHeld
41
+ * @property {(address: string, startedAt: number) => number} clearUpAfter
42
+ */
43
+
44
+ /**
45
+ * How long nothing is placed on an output whose input has just gone, and the
46
+ * ceiling that doubling reaches.
47
+ *
48
+ * Both are chosen, and are named here as chosen rather than dressed as
49
+ * measurements: what they bound is not how long the data takes to come back —
50
+ * that is the swarm's business and nobody here can know it — but how often it
51
+ * is worth asking. They replace the same two figures, with the same values,
52
+ * that lived in the session manager and governed only the dead run's own retry
53
+ * while the plan placed fresh runs beside it every half second.
54
+ */
55
+ const INPUT_QUIET_BASE_MS = 2_000;
56
+ const INPUT_QUIET_MAX_MS = 15_000;
57
+ const START_FAST_FAIL_MS = 2_000;
58
+ const MAX_FAILED_STARTS = 3;
59
+
60
+ export class EncodeOrchestrator {
61
+ /** Derived priority maps. Discardable and rebuilt from viewer state. */
62
+ #demand = new SegmentDemand();
63
+ /** @type {(address: string) => string} */
64
+ #describeWaits = () => "";
65
+
66
+ /** Output address to what has been made of it. @type {Map<string, CoverageMap>} */
67
+ #coverage = new Map();
68
+
69
+ /** @type {SegmentCoverage | null} */
70
+ #segmentCoverage = null;
71
+
72
+ /** Output address to the runs on it. @type {Map<string, import("../encode/EncodeRun.js").EncodeRun[]>} */
73
+ #runs = new Map();
74
+
75
+ /** Last state after an output has no registered run. @type {Map<string, string>} */
76
+ #lastState = new Map();
77
+
78
+ /** Last encoder error per output. @type {Map<string, string>} */
79
+ #lastError = new Map();
80
+
81
+ /** Last progress snapshot per output after its run ends. @type {Map<string, object>} */
82
+ #lastProgress = new Map();
83
+
84
+ /** Consecutive fast failures at one position, per output. @type {Map<string, { at: number, count: number }>} */
85
+ #failedStarts = new Map();
86
+
87
+ /** How runs have ended, by cause. @type {Map<string, number>} */
88
+ #endings = new Map();
89
+
90
+ /**
91
+ * How many times in a row an output's run has died because its input was not
92
+ * there. Cleared only by a run that PRODUCED something, which is the only
93
+ * proof that the input can be read — see `#noteInputAvailability`.
94
+ *
95
+ * @type {Map<string, number>}
96
+ */
97
+ #inputLostAttempts = new Map();
98
+
99
+ /** Output address to the time before which nothing is placed on it. @type {Map<string, number>} */
100
+ #quietUntil = new Map();
101
+
102
+ /** The wake-up per output, so a quiet output is reconsidered. @type {Map<string, NodeJS.Timeout>} */
103
+ #quietTimers = new Map();
104
+
105
+ /** The last state said out loud, so an unchanged state is not repeated. */
106
+ #lastDescribed = "";
107
+
108
+ /** What a stop and a start have cost on this host. */
109
+ #costs = new RunCosts();
110
+
111
+ /**
112
+ * What starting and stopping an encoder was measured to cost on this host,
113
+ * before any viewer existed. Told once; real runs replace it as they end.
114
+ *
115
+ * @param {{ firstByteWaitSec: number, killCostSec: number } | null} measured
116
+ * @returns {void}
117
+ */
118
+ noteStartupCosts(measured) {
119
+ this.#costs.noteStartup(measured);
120
+ }
121
+
122
+ /** Derived segment demand for one output, copied from the discardable cache. */
123
+ wantedSegmentsOn(address) {
124
+ return [...this.#demand.mapOn(address)];
125
+ }
126
+
127
+ /** The last reason a budget was cut, so the same one is not said twice. */
128
+ #lastBudgetReason = new Map();
129
+
130
+ /** The last unmet want said out loud, so a stuck one is said once. */
131
+ #lastUnmet = new Map();
132
+
133
+ /** The last time the machine bound an output's encoders, so it is said once. */
134
+ #lastMachineBound = new Map();
135
+
136
+ /**
137
+ * @param {object} params
138
+ * @param {(address: string) => number} params.maxRunsFor - How many encoders
139
+ * this machine can afford on one output. The same arithmetic that decides
140
+ * the quality offer; measured per host, never chosen here.
141
+ * @param {(params: { address: string, from: number, to: number, because: string }) =>
142
+ * import("../encode/EncodeRun.js").EncodeRun} params.makeRun - Build a run
143
+ * for a stretch. What to read, what to map and how to cut belong to whoever
144
+ * knows the source.
145
+ * @param {number} params.segmentSeconds
146
+ * @param {import("../encode/contention.js").ContentionPenalties | null}
147
+ * [params.contentionPenalties] - How much slower one encoder runs beside
148
+ * others, MEASURED on this host at startup and keyed by how many others
149
+ * there are. Null until something has measured it, and then the penalty is
150
+ * 1 — a number invented here would be the same mistake as an invented
151
+ * encoding speed.
152
+ * @param {{ info: (line: string) => void, warn: (line: string) => void }} params.logger
153
+ * @param {() => number} [params.now]
154
+ * @param {(address: string) => string} [params.describeWaits] - What the
155
+ * viewers actually waited for on this output, by band, for the state line.
156
+ * HANDED IN: what anybody waited for belongs to the priority layer, and
157
+ * this one may be asked about encoders with no ledger, no clock and no
158
+ * viewer anywhere. Absent, the line simply does not carry it.
159
+ * @param {SegmentCoverage | null} [params.segmentCoverage]
160
+ */
161
+ constructor({
162
+ maxRunsFor,
163
+ makeRun,
164
+ segmentSeconds,
165
+ contentionPenalties = null,
166
+ refetchSecPerFilmSecond = () => 0,
167
+ startingSpeedFor = () => 0,
168
+ segmentCoverage = null,
169
+ planSoon = null,
170
+ describeWaits = null,
171
+ admission = null,
172
+ logger,
173
+ now
174
+ }) {
175
+ // HOW MANY ENCODERS THE WHOLE MACHINE HOLDS, across outputs. `maxRunsFor`
176
+ // answers for one output as though it were alone; this is what refuses the
177
+ // encoder that would slow everybody below realtime. Absent in a check that
178
+ // is about one output, and then only the per-output limit binds.
179
+ this.admission = admission && typeof admission.placesFor === "function" ? admission : null;
180
+ this.#describeWaits = typeof describeWaits === "function" ? describeWaits : () => "";
181
+ // Only the segment facts and operations this planner needs cross the
182
+ // storage boundary; the concrete storage remains in the server assembly.
183
+ this.#segmentCoverage = segmentCoverage;
184
+ this.maxRunsFor = maxRunsFor;
185
+ // Seconds of swarm time per second of film: what re-encoding material that
186
+ // already exists costs the download, over and above the encoder's own time.
187
+ // Injected, because the film's byte rate and the swarm's are measured
188
+ // elsewhere and this class must not reach for them.
189
+ this.refetchSecPerFilmSecond = refetchSecPerFilmSecond;
190
+ // Measured per host: what a second encoder costs the first. Unmeasured is 1,
191
+ // and then only the budget bounds how many there are.
192
+ this.contentionPenalties = contentionPenalties instanceof Map ? contentionPenalties : null;
193
+ // WHAT THIS HOST ENCODES AT BEFORE ANY RUN HAS REPORTED. The startup
194
+ // benchmark measures it — a real pipeline over real clips, before a viewer
195
+ // exists — so the plan is never asked to compare arrivals with no speed to
196
+ // compute them from. Every run that then works refines it.
197
+ this.startingSpeedFor = startingSpeedFor;
198
+ this.makeRun = makeRun;
199
+ this.segmentSeconds = segmentSeconds;
200
+ this.logger = logger;
201
+ this.now = typeof now === "function" ? now : Date.now;
202
+ // Asked for, not commanded: this class decides, and something else owns the
203
+ // loop that calls it. Absent in a test, where the clock is the test's own.
204
+ this.planSoon = typeof planSoon === "function" ? planSoon : () => undefined;
205
+ }
206
+
207
+ /**
208
+ * The map of one output, made on first mention.
209
+ *
210
+ * @param {string} address
211
+ * @returns {CoverageMap}
212
+ */
213
+ coverageOf(address) {
214
+ let map = this.#coverage.get(address);
215
+ if (!map) {
216
+ map = new CoverageMap();
217
+ this.#coverage.set(address, map);
218
+ }
219
+ return map;
220
+ }
221
+
222
+ /**
223
+ * Put the map's picture of what is ready back in step with the disk.
224
+ *
225
+ * ONE AUTHORITY ON WHAT EXISTS, AND IT IS THE STORE. The map holds no memory
226
+ * of readiness between calls: it is handed the whole answer, replacing
227
+ * whatever it had, immediately before anything is decided from it. So a
228
+ * segment whose file was discarded with the run that had it open, dropped to
229
+ * make room, or reopened by a run restarting on it stops being ready in the
230
+ * same breath — without anything having to notice and say so.
231
+ *
232
+ * The map used to be filled from outside, by the session manager, with a
233
+ * method that only ever added. Nothing anywhere took a number back. Field
234
+ * 2026-09-07: the map claimed all 482 segments of a film while the directory
235
+ * held nothing, so every arrangement scored perfect, the only encoder was
236
+ * stopped as unnecessary and none was placed again — two sessions in a row
237
+ * with no picture at all.
238
+ *
239
+ * A store is optional here only in the sense that an authority which was not
240
+ * supplied cannot be consulted: without one the map keeps what it was told
241
+ * directly, which is how this class is exercised with plain numbers.
242
+ *
243
+ * @param {string} address
244
+ * @returns {CoverageMap}
245
+ */
246
+ #upToDateCoverage(address) {
247
+ const coverage = this.coverageOf(address);
248
+ if (this.#segmentCoverage) {
249
+ coverage.setReady(this.#segmentCoverage.provenNumbers(address));
250
+ }
251
+ return coverage;
252
+ }
253
+
254
+ /**
255
+ * Where a run started here must stop: the free stretch in front of it.
256
+ *
257
+ * Asked of the one map, brought up to date first. It used to be worked out by
258
+ * the session manager, which reached into this layer for the map and into the
259
+ * store for what was on the disk and put the two together itself — one fact
260
+ * with two owners and a third party carrying it between them, which is how the
261
+ * two came to disagree.
262
+ *
263
+ * @param {object} params
264
+ * @param {string} params.address
265
+ * @param {number} params.from - Where the run will start.
266
+ * @param {object | null} [params.exceptRun] - The run being replaced, whose
267
+ * own claim is not somebody else's material.
268
+ * @param {number} [params.segmentCount] - The output's length, when known.
269
+ * @returns {number} The last number to work through, or `-1` for the end of
270
+ * the film.
271
+ */
272
+ freeStretchEnd({ address, from, exceptRun = null, segmentCount = 0 }) {
273
+ if (!address) {
274
+ return -1;
275
+ }
276
+ if (segmentCount > 0) {
277
+ this.coverageOf(address).setSegmentCount(segmentCount);
278
+ }
279
+ const coverage = this.#upToDateCoverage(address);
280
+ const start = Math.max(0, from);
281
+ const free = coverage.freeRunFrom(start, exceptRun);
282
+ if (!Number.isFinite(free)) {
283
+ return -1;
284
+ }
285
+ const end = start + Math.max(1, free) - 1;
286
+ return segmentCount > 0 && end >= segmentCount - 1 ? -1 : end;
287
+ }
288
+
289
+ /**
290
+ * @param {string} address
291
+ * @returns {import("../encode/EncodeRun.js").EncodeRun[]}
292
+ */
293
+ runsOn(address) {
294
+ return this.#runs.get(address) ?? [];
295
+ }
296
+
297
+ /**
298
+ * The aggregate state of this output's current runs, or its last ending when
299
+ * none remain.
300
+ *
301
+ * @param {string} address
302
+ * @returns {string}
303
+ */
304
+ stateOf(address) {
305
+ const runs = this.runsOn(address);
306
+ return runs.length > 0 ? runStateOf(runs) : (this.#lastState.get(address) ?? runStateOf([]));
307
+ }
308
+
309
+ /** @param {string} address @returns {string} */
310
+ errorOf(address) {
311
+ return this.#lastError.get(address) ?? "";
312
+ }
313
+
314
+ /**
315
+ * Progress of the live run that covers a position, or the most recently
316
+ * updated run when no position is supplied.
317
+ *
318
+ * @param {string} address
319
+ * @param {number | null} [index]
320
+ * @returns {object | null}
321
+ */
322
+ progressOf(address, index = null) {
323
+ const live = this.runsOn(address).filter((run) => run.isAlive);
324
+ const covering = Number.isInteger(index)
325
+ ? live.filter((run) => run.from <= index && endOfRun(run) >= index)
326
+ : live;
327
+ const candidates = covering.length > 0 ? covering : live;
328
+ const run = [...candidates].sort(
329
+ (left, right) => (right.progress?.updatedAt ?? 0) - (left.progress?.updatedAt ?? 0)
330
+ )[0];
331
+ return run?.progress?.snapshot?.() ?? this.#lastProgress.get(address) ?? null;
332
+ }
333
+
334
+ /**
335
+ * Whether another start at this position is allowed.
336
+ *
337
+ * @param {string} address
338
+ * @param {number} from
339
+ * @returns {boolean}
340
+ */
341
+ mayStartAt(address, from) {
342
+ const failed = this.#failedStarts.get(address);
343
+ return failed?.at !== from || failed.count < MAX_FAILED_STARTS;
344
+ }
345
+
346
+ /**
347
+ * Record whether a failed run died before it performed sustained work.
348
+ *
349
+ * @param {string} address
350
+ * @param {number} from
351
+ * @param {number} livedMs
352
+ * @returns {{ at: number, count: number, blocked: boolean, limit: number, fastMs: number }}
353
+ */
354
+ noteStartFailure(address, from, livedMs) {
355
+ if (!(livedMs < START_FAST_FAIL_MS)) {
356
+ this.#failedStarts.delete(address);
357
+ return { at: -1, count: 0, blocked: false, limit: MAX_FAILED_STARTS, fastMs: START_FAST_FAIL_MS };
358
+ }
359
+ const previous = this.#failedStarts.get(address);
360
+ const next = {
361
+ at: from,
362
+ count: previous?.at === from ? previous.count + 1 : 1
363
+ };
364
+ this.#failedStarts.set(address, next);
365
+ return {
366
+ ...next,
367
+ blocked: next.count >= MAX_FAILED_STARTS,
368
+ limit: MAX_FAILED_STARTS,
369
+ fastMs: START_FAST_FAIL_MS
370
+ };
371
+ }
372
+
373
+ /**
374
+ * An output that no longer exists and has no run left on it.
375
+ *
376
+ * How its last run ended, what went wrong and which position kept failing are
377
+ * facts about THAT output. The name follows from the key, so the next output
378
+ * with the same parameters has the same address; kept, those facts would
379
+ * greet it as its own — a failed ending makes its first wait throw before any
380
+ * encoder is placed, and nothing would ever clear it.
381
+ *
382
+ * @param {string} address
383
+ */
384
+ forgetOutput(address) {
385
+ if (this.runsOn(address).length > 0) {
386
+ return;
387
+ }
388
+ this.#lastState.delete(address);
389
+ this.#lastError.delete(address);
390
+ this.#lastProgress.delete(address);
391
+ this.#failedStarts.delete(address);
392
+ }
393
+
394
+ /** @param {string} address @returns {{ at: number, count: number, blocked: boolean, limit: number }} */
395
+ startFailureOf(address) {
396
+ const failure = this.#failedStarts.get(address) ?? { at: -1, count: 0 };
397
+ return { ...failure, blocked: failure.count >= MAX_FAILED_STARTS, limit: MAX_FAILED_STARTS };
398
+ }
399
+
400
+ /**
401
+ * What the map says about one segment of one output, and about the map it
402
+ * sits in.
403
+ *
404
+ * Asked by whoever is holding a request and measuring the wait: a wait means
405
+ * one thing at the top rank and another at the bottom, and telling them apart
406
+ * needs both the segment's own rank and the highest rank stated, since a rank
407
+ * is a position in this map and not an absolute number.
408
+ *
409
+ * AND AN EMPTY MAP IS NOT AN ANSWER. A top rank of zero says the map has not
410
+ * been built yet — a session created a moment ago, before the first pass —
411
+ * and that is a different thing from "nobody is coming". Conflated, every
412
+ * request behind the run reads as absent for as long as a fresh session has
413
+ * no map.
414
+ *
415
+ * It exists because the one caller reached through this object into the store
416
+ * behind it. A reach like that is how a store becomes the surface: the day it
417
+ * changes, a caller two layers away breaks for a reason it cannot see.
418
+ *
419
+ * @param {string} address
420
+ * @param {number} index
421
+ * @returns {{ rank: number, topRank: number }}
422
+ */
423
+ rankAt(address, index) {
424
+ return this.#demand.rankOf(address, index);
425
+ }
426
+
427
+ /**
428
+ * How many encoder processes are running on this machine right now, over
429
+ * every output.
430
+ *
431
+ * ONE COUNT, and it is this class's because this class is what makes and
432
+ * unmakes runs: adopted the moment one exists and forgotten the moment one
433
+ * ends, both synchronously. The session manager answered the same question
434
+ * twice by walking its own registry — once per SESSION and once per RUN —
435
+ * which agreed only while a session held at most one run. It has held several
436
+ * since the plan was allowed to place them, and the per-session count is the
437
+ * wrong one of the two wherever they differ: what a second encoder costs was
438
+ * measured between ffmpeg PROCESSES, not between outputs.
439
+ *
440
+ * A SUSPENDED run is not counted. It is stopped where it stands and is using
441
+ * nothing; a cost measured beside it is a cost measured alone.
442
+ *
443
+ * @returns {number}
444
+ */
445
+ /**
446
+ * How many encoders are alive on each output, suspended ones included.
447
+ *
448
+ * What the machine-wide admission counts as holding a place. A suspended
449
+ * encoder is counted here, unlike in {@link runningCount}: that one answers
450
+ * what is competing for the processor this instant, this one what the
451
+ * machine is committed to — and a parked encoder resumes the moment the
452
+ * viewer catches up.
453
+ *
454
+ * @returns {Map<string, number>}
455
+ */
456
+ liveRunsByAddress() {
457
+ /** @type {Map<string, number>} */
458
+ const byAddress = new Map();
459
+ for (const [address, runs] of this.#runs) {
460
+ const alive = runs.filter((run) => run.isAlive).length;
461
+ if (alive > 0) {
462
+ byAddress.set(address, alive);
463
+ }
464
+ }
465
+ return byAddress;
466
+ }
467
+
468
+ runningCount() {
469
+ let running = 0;
470
+ for (const runs of this.#runs.values()) {
471
+ for (const run of runs) {
472
+ if (run.isAlive && !run.isSuspended) {
473
+ running += 1;
474
+ }
475
+ }
476
+ }
477
+ return running;
478
+ }
479
+
480
+ /**
481
+ * How long an output is, once its playlist is known.
482
+ *
483
+ * @param {string} address
484
+ * @param {number} segmentCount
485
+ */
486
+ setSegmentCount(address, segmentCount) {
487
+ this.coverageOf(address).setSegmentCount(segmentCount);
488
+ }
489
+
490
+ /**
491
+ * Segments that already exist — from a previous life of this process, or
492
+ * because somebody else made them. Told to the map, which is what stops an
493
+ * encoder being started to make them again.
494
+ *
495
+ * @param {string} address
496
+ * @param {Iterable<number>} indexes
497
+ */
498
+ noteAlreadyMade(address, indexes) {
499
+ for (const index of indexes) {
500
+ this.noteProduced(address, index);
501
+ }
502
+ }
503
+
504
+ /**
505
+ * A viewer states what it is waiting for. Replaces whatever it said before.
506
+ *
507
+ * @param {object} params
508
+ * @param {string} params.claimant
509
+ * @param {string} params.address
510
+ * @param {number} params.from
511
+ * @param {number} params.to
512
+ * @param {number} [params.priority] - Higher is sooner. One viewer states
513
+ * several stretches at once — what must be ready before they set off, what
514
+ * is reachable while they watch it, the rest of the track — and the filling
515
+ * takes them in this order. Absent means one undifferentiated want, which
516
+ * is what a caller that knows only a position states.
517
+ */
518
+ /**
519
+ * What is wanted of one output, in its own segment numbers.
520
+ *
521
+ * ONE MAP, ALREADY MERGED, AND WITH NOBODY'S NAME ON IT. It is built once per
522
+ * film by the layer that knows where the viewers are; this layer receives it
523
+ * converted into an output's own numbering and never asks who is in it.
524
+ *
525
+ * That replaced a window per viewer per band stated here and merged here,
526
+ * which was the same work done twice in two layers, with the viewer's name as
527
+ * the key of a claim — against the rule that the encoding and the viewer are
528
+ * not connected at all.
529
+ *
530
+ * An empty map says nobody is coming anywhere in this output, and the plan
531
+ * stops its encoders for it. Nothing has to be released when somebody leaves:
532
+ * the map that arrives next simply does not have them in it.
533
+ *
534
+ * @param {string} address
535
+ * @param {{ from: number, to: number, priority: number, withinSeconds: number }[]} zones
536
+ */
537
+ notePriorityMap(address, zones) {
538
+ this.#demand.state(address, zones);
539
+ // NOBODY IS COMING HERE, so what was remembered about this output's input
540
+ // is about nobody. Kept, those three entries would stay for the life of the
541
+ // process, and the wait they describe would greet whoever opens this output
542
+ // next — a viewer arriving is new information, and one attempt for them is
543
+ // right whatever the last one met.
544
+ if (!Array.isArray(zones) || zones.length === 0) {
545
+ this.#forgetInputState(address);
546
+ }
547
+ }
548
+
549
+ /**
550
+ * A segment has been finished, by whichever run made it.
551
+ *
552
+ * @param {string} address
553
+ * @param {number} index
554
+ */
555
+ noteProduced(address, index) {
556
+ // Nothing is told to the store: by the time this is called the piece is
557
+ // ALREADY under its served name, because the rename is what closing it
558
+ // means. A statement kept beside the disk would be a second owner of one
559
+ // fact, which removed the stale second owner from the coverage map.
560
+ this.coverageOf(address).markReady(index);
561
+ this.#segmentCoverage?.announce?.(address, index);
562
+ for (const run of this.runsOn(address)) {
563
+ run.noteProduced(index);
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Decide and act, for every output anybody wants anything of and every output
569
+ * that still has an encoder on it.
570
+ *
571
+ * Safe to call as often as anything changes: the plan is a function of the
572
+ * state, so a pass that finds nothing to change does nothing.
573
+ */
574
+ reconcile() {
575
+ const addresses = new Set([...this.#demand.addresses(), ...this.#runs.keys()]);
576
+ for (const address of addresses) {
577
+ this.#reconcileOne(address);
578
+ }
579
+ // WHAT THIS CLASS BELIEVES, said by this class. `describe()` was written
580
+ // and called from nowhere, so on 2026-09-05 the question "why did the plan
581
+ // not see the gap the viewer was stopped at" had to be answered by
582
+ // inference from start and stop lines, and was not answered at all.
583
+ //
584
+ // Printed on CHANGE rather than on a timer: a quiet session says nothing, a
585
+ // session that is deciding something says what it decided, and there is no
586
+ // interval to choose.
587
+ const state = this.describe();
588
+ if (state !== this.#lastDescribed) {
589
+ this.#lastDescribed = state;
590
+ this.logger.info(state);
591
+ }
592
+ }
593
+
594
+ /**
595
+ * @param {string} address
596
+ */
597
+ #reconcileOne(address) {
598
+ // WHAT EXISTS IS ASKED OF THE DISK, HERE, EVERY TIME. The plan is arithmetic
599
+ // over what is made, what is being made and what is wanted, and the first of
600
+ // those is not this layer's to remember.
601
+ const coverage = this.#upToDateCoverage(address);
602
+ // A run that has ended and said nothing. One built here reports its own
603
+ // ending and is released by `noteEnded`; one ADOPTED from elsewhere — a
604
+ // session whose encoder stopped — has no such promise, and its claim would
605
+ // otherwise sit in the map for the life of the process, telling the plan
606
+ // that a stretch nobody is making is being made. Nothing would ever be
607
+ // started there again.
608
+ for (const run of this.runsOn(address)) {
609
+ if (!run.isAlive && !run.isStopping) {
610
+ this.noteEnded({
611
+ address,
612
+ run,
613
+ ending: ENCODE_EXIT.GONE,
614
+ because: "it is no longer running, and it did not say so"
615
+ });
616
+ }
617
+ }
618
+ // ITS INPUT WAS NOT THERE A MOMENT AGO, so nothing is placed yet. The sweep
619
+ // above still runs — a claim left by a dead run must be released whatever
620
+ // the reason — and only the placing waits. This is the one thing that makes
621
+ // the delay bind: it used to be timed against the dead run, which the plan
622
+ // does not consult, so a fresh run went to the same place as fast as ffmpeg
623
+ // could fail there.
624
+ //
625
+ // AND ONLY WHILE NOTHING IS PRODUCING THERE. A run still alive on this
626
+ // output is proof the input can be read, whatever a run beside it met, so
627
+ // the wait must not silence an output that is working.
628
+ if (this.#isQuiet(address) && this.runsOn(address).every((run) => !run.isAlive)) {
629
+ return;
630
+ }
631
+ // ONE MAP, NOT ONE WINDOW PER VIEWER PER ZONE.
632
+ //
633
+ // Two viewers a few seconds apart state stretches that overlap, and the plan
634
+ // puts one encoder on each stretch it is given — so unmerged windows buy an
635
+ // encoder per viewer for film they both want, which is the opposite of what
636
+ // sharing the output is for. Merged, the highest rank and the soonest time
637
+ // per number win and the stretches do not overlap, so one encoder serves
638
+ // everyone standing in front of it.
639
+ //
640
+ // Asked of the register, which is the thing that holds the windows. This
641
+ // used to reach into the layer that STATES them for the same arithmetic,
642
+ // which is the coupling the layer rule forbids; the arithmetic itself now
643
+ // lives where it belongs to nobody.
644
+ const windows = this.#demand.mapOn(address);
645
+ const live = this.runsOn(address).filter((run) => run.isAlive);
646
+ // Asked ONCE. It is arithmetic over measurements, but it also says out loud
647
+ // when the reason it cuts the budget changes, so asking it three times in
648
+ // one pass is three chances to say a thing that happened once.
649
+ const maxRuns = this.#withinMachine(address, live, this.#affordableOn(address, live));
650
+ // THE TERMS EVERY ARRIVAL IS COMPUTED FROM, named here so the line below can
651
+ // print them. A decision of this plan is `delay + (index - at) / rate +
652
+ // madeBetween * refetch` against a deadline, so without the rate and the two
653
+ // prices no recorded decision can be reproduced — which is what happened
654
+ // with the one-piece intervals of 2026-09-08: the rate was substituted six
655
+ // times from the speeds the session reported elsewhere and none of them gave
656
+ // the answer the plan had given.
657
+ const costs = this.#costs.seconds();
658
+ const refetchSecPerFilmSecond = this.refetchSecPerFilmSecond(address);
659
+ const speedX = this.#speedOn(address, live);
660
+ const actions = planEncoders({
661
+ coverage,
662
+ windows,
663
+ // The runs themselves. The plan is arithmetic and reads four numbers off
664
+ // each; what it hands back names the run by BEING it, so nothing has to
665
+ // invent a token to refer to one by.
666
+ runs: live,
667
+ maxRuns,
668
+ segmentSeconds: this.segmentSeconds,
669
+ // What a start and a kill cost, measured from this host's own runs rather
670
+ // than written into the code from one machine's reading. Zero until
671
+ // something has been measured, which is the same convention as the
672
+ // refetch price and is stated so the bias is known.
673
+ ...costs,
674
+ // What a second of film costs to fetch again, in seconds of swarm time.
675
+ // Answered by whoever measures the film's own byte rate and the swarm's;
676
+ // zero until they have, which makes driving through look cheaper than it
677
+ // is and is stated here so the bias is known.
678
+ refetchSecPerFilmSecond,
679
+ // How much slower one encoder runs beside others, read off this host's own
680
+ // startup measurement. A pure function over a measured table: beyond what
681
+ // was measured it holds the largest reading rather than continuing a curve
682
+ // nothing observed.
683
+ contentionPenaltyFor: (others) => contentionPenalty(others, this.contentionPenalties).penalty,
684
+ speedX
685
+ });
686
+
687
+ // A move is the plan taking a running encoder away from where it already
688
+ // stands, which is exactly the decision that was found wandering back and
689
+ // forth in the field on 2026-09-07 with no way to see why: the "because"
690
+ // line names the comparison in words, never the numbers it was decided
691
+ // from. Said here, once per reconcile, and only when a move actually
692
+ // happens — everything a rerun of the same decision needs: the windows
693
+ // this call saw (priority, the real time, which side of the viewers),
694
+ // the budget, and where every live run stood.
695
+ // WHAT WAS DECIDED AND WITH WHAT INTERVAL, said whenever anything is placed
696
+ // or taken away — not only on a move.
697
+ //
698
+ // Field 2026-09-08 could not be diagnosed from this line: it printed the
699
+ // windows, the budget and where the live runs stood, and NOT the intervals
700
+ // the actions carried. What the session actually did was give every encoder
701
+ // an interval of exactly ONE segment — 63 runs, each making one piece and
702
+ // exiting, twelve of them normally — and the reasons printed beside them
703
+ // read as moves, so the fault was diagnosed three times as something it was
704
+ // not. An interval is what a run is, and it was the one thing missing.
705
+ //
706
+ // AND THE TERMS, for the same reason one step further: an interval says what
707
+ // was decided and the terms say why. `speed` is what every arrival is
708
+ // divided by, so a decision recorded without it can be re-read and not
709
+ // recomputed; `firstByte` and `kill` are what a start and a stop cost here;
710
+ // `refetch` is what a second of film costs to fetch again. A zero in the
711
+ // last three is a measurement nobody has taken, not a free operation, and it
712
+ // is printed so that reading it as free is a choice rather than an accident.
713
+ if (actions.some((action) => action.type !== "keep")) {
714
+ this.logger.info(
715
+ `encode-plan on ${address}: ` +
716
+ `${actions.map((action) => `${action.type} #${action.from ?? "?"}..#${action.to ?? "?"}`).join(", ")}` +
717
+ ` [speed=${speedX.toFixed(2)}x firstByte=${costs.firstByteWaitSec.toFixed(2)}s ` +
718
+ `kill=${costs.killCostSec.toFixed(2)}s refetch=${refetchSecPerFilmSecond.toFixed(3)}s/s ` +
719
+ `maxRuns=${maxRuns} live=${live.length}]`
720
+ );
721
+ }
722
+ if (actions.some((action) => action.type === "move")) {
723
+ this.logger.info(
724
+ `encode-plan move on ${address}: windows=${JSON.stringify(windows)} ` +
725
+ `maxRuns=${maxRuns} ` +
726
+ `live=${JSON.stringify(live.map((run) => ({ from: run.from, to: run.to, head: run.head, speedX: run.speedX })))}`
727
+ );
728
+ }
729
+ for (const action of actions) {
730
+ if (action.type === "stop") {
731
+ this.#stop(action.run, action.because);
732
+ continue;
733
+ }
734
+ if (action.type === "move") {
735
+ // A running encoder's position cannot be changed — it is fixed when the
736
+ // process starts — so a move is this one ending and another beginning
737
+ // where the material is missing. Both halves are recorded as what they
738
+ // are, which is why the ending of a moved run is not called normal.
739
+ this.#stop(action.run, action.because);
740
+ this.#start(address, action.from, action.to, action.because);
741
+ continue;
742
+ }
743
+ if (action.type === "start") {
744
+ this.#start(address, action.from, action.to, action.because);
745
+ continue;
746
+ }
747
+ // A run that stays keeps its claim current: the free stretch ahead of it
748
+ // may have shrunk since it was given one.
749
+ //
750
+ // THE CLAIM IS THE STRETCH IT WAS GIVEN, and there is one rule for that
751
+ // everywhere. It used to be narrowed here to what the run had already
752
+ // MADE whenever the run had no end, which meant a run claimed the single
753
+ // number it was writing and nothing beyond. The plan then read the road
754
+ // in front of a working encoder as free and started more encoders on it:
755
+ // three processes writing one directory with the same names, field
756
+ // 2026-09-06, and a piece of the film lost for good when the first of
757
+ // them was cleaned up after.
758
+ //
759
+ // The worry that narrowing was written for is real and is answered where
760
+ // it belongs — a viewer opening the same film further in must not find
761
+ // every number taken. That is the plan's business, and the plan can take
762
+ // road away from a run that has no end, because such a run carries no
763
+ // `-to` and simply stops when its head meets somebody else's claim.
764
+ coverage.claim(action.run, action.from, endOfRun({ from: action.from, to: action.to }));
765
+ }
766
+
767
+ // NOBODY IS MAKING WHAT SOMEBODY IS WAITING FOR. Said here, with the numbers
768
+ // the decision was taken from, because it is the one state in which a viewer
769
+ // waits for ever and every line above it reads as a healthy proxy.
770
+ //
771
+ // Field 2026-09-07, twice in one evening: the last word about an output was
772
+ // "the film is no worse off without it", and after it nothing — no run, no
773
+ // refusal, no answer to the browser's request for the header. The wait ended
774
+ // at the browser's own timeout with a message naming no cause, and the
775
+ // proxy's log named none either.
776
+ //
777
+ // SAID ONCE PER STATE, not once per pass. A stuck output is reconciled on
778
+ // every event that touches it, and a line repeated for as long as the state
779
+ // lasts is what buried the last one: 49 295 copies of `send queue stuck` in
780
+ // a 159 090-line file, 31 % of the log, all of one wedge.
781
+ const wanting = firstUnmetWant(coverage, windows);
782
+ const stillRunning = this.runsOn(address).filter((run) => run.isAlive);
783
+ if (wanting === null || stillRunning.length > 0) {
784
+ this.#lastUnmet.delete(address);
785
+ } else if (this.#lastUnmet.get(address) !== wanting) {
786
+ this.#lastUnmet.set(address, wanting);
787
+ const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
788
+ this.logger.warn(
789
+ `encode: #${wanting} of ${address} is wanted and NO ENCODER IS MAKING IT — ` +
790
+ `ready=${coverage.stats().ready} of ${coverage.segmentCount} ` +
791
+ `files=${held < 0 ? "?" : held} maxRuns=${maxRuns} ` +
792
+ `windows=${JSON.stringify(windows)}`
793
+ );
794
+ }
795
+ }
796
+
797
+ /**
798
+ * @param {string} address
799
+ * @param {number} from
800
+ * @param {number} to
801
+ * @param {string} because
802
+ */
803
+ #start(address, from, to, because) {
804
+ // The encoder is built here and now: whoever builds one waits for nothing,
805
+ // so it exists by the time this line returns. That is what makes the
806
+ // stretch held from this instant — this class knows what it is making
807
+ // because it has just made it, and no second encoder can be started for the
808
+ // same stretch on the next pass.
809
+ //
810
+ // It was not always so. The builder used to answer with nothing and start
811
+ // the encoder behind the answer, so the stretch stayed FREE for as long as
812
+ // that took, and every pass in between started another one: 684 starts in
813
+ // 482 seconds of field 2026-09-05, of which 973 answers said the encoder
814
+ // was not there yet — every start without exception.
815
+ //
816
+ // The run names itself: identity is a property of the thing, and two
817
+ // places minting names is how one stops being unique.
818
+ const run = this.makeRun({ address, from, to, because });
819
+ if (!run) {
820
+ // A refusal, not a wait: no session serves this output, or this position
821
+ // has failed to start too many times running.
822
+ this.logger.warn(`encode: no encoder could be made for #${from}..#${to} of ${address}`);
823
+ return;
824
+ }
825
+ const onThisOutput = this.#runs.get(address) ?? [];
826
+ onThisOutput.push(run);
827
+ this.#runs.set(address, onThisOutput);
828
+ // Nothing has to be un-proved when a run takes a stretch that has already
829
+ // been written. A piece is only ever NAMED as served once it is closed, and
830
+ // a run writing that number again writes under a working name until it
831
+ // closes its own — so the file standing there is a complete piece made by
832
+ // somebody, and serving it is right until the newer one replaces it whole.
833
+ // The claim comes after the run exists, and that is not a race: everything
834
+ // between is synchronous, and a process cannot say a word before the next
835
+ // tick. What it removes is the second act — building a run and starting it
836
+ // were two steps, and two owners each performed the second one.
837
+ this.coverageOf(address).claim(run, from, endOfRun({ from, to }));
838
+ }
839
+
840
+ /**
841
+ * The best figure this host has for one encoder on this output: the
842
+ * processing speed a run here has measured (`EncodeRun.speedX`), or what this
843
+ * output was last measured doing and the startup measurements predict
844
+ * (`startingSpeedFor`), which exists before any run has closed two pieces and
845
+ * after a restart. The run owns its speed; nothing here keeps a copy.
846
+ *
847
+ * It is the MACHINE's speed: input waits for the swarm are not in it. What
848
+ * the swarm delivers is the separate supply term
849
+ * (`refetchSecPerFilmSecond`).
850
+ *
851
+ * @param {string} address
852
+ * @param {{ speedX: number }[]} live
853
+ * @returns {number}
854
+ */
855
+ #speedOn(address, live) {
856
+ return Math.max(
857
+ live.reduce((best, run) => Math.max(best, run.speedX || 0), 0),
858
+ this.startingSpeedFor(address) || 0
859
+ );
860
+ }
861
+
862
+ /**
863
+ * How many encoders may run on this output, from every limit at once.
864
+ *
865
+ * The processor is one of them and is answered from outside, where the
866
+ * machine is measured. The other two are known here: what the swarm delivers,
867
+ * through the seconds of swarm time a second of film costs, and — once it is
868
+ * supplied — the memory the piece store may hold against what one encoder's
869
+ * reader keeps.
870
+ *
871
+ * Said out loud when it is not the processor that decided, because "why is
872
+ * there only one encoder" is otherwise a question no log can answer.
873
+ *
874
+ * @param {string} address
875
+ * @param {{ speedX: number }[]} live
876
+ * @returns {number}
877
+ */
878
+ #affordableOn(address, live) {
879
+ const byProcessor = Math.max(0, this.maxRunsFor(address));
880
+ const fastest = this.#speedOn(address, live);
881
+ const budget = affordableRuns({
882
+ byProcessor,
883
+ speedX: fastest,
884
+ refetchSecPerFilmSecond: this.refetchSecPerFilmSecond(address),
885
+ // How much slower one encoder runs beside others, read off this host's own
886
+ // startup measurement. A pure function over a measured table: beyond what
887
+ // was measured it holds the largest reading rather than continuing a curve
888
+ // nothing observed.
889
+ contentionPenaltyFor: (others) => contentionPenalty(others, this.contentionPenalties).penalty
890
+ });
891
+ if (budget.runs !== byProcessor && budget.because !== this.#lastBudgetReason.get(address)) {
892
+ this.#lastBudgetReason.set(address, budget.because);
893
+ this.logger.info(
894
+ `encode: ${budget.runs} encoder(s) on ${address.slice(0, 60)} — ${budget.because} ` +
895
+ `(the processor alone would allow ${byProcessor})`
896
+ );
897
+ }
898
+ return budget.runs;
899
+ }
900
+
901
+ /**
902
+ * The per-output limit, bounded by what the whole machine can still hold.
903
+ *
904
+ * The per-output answer is at least one whatever else is running; the
905
+ * machine's may be none, and that is the refusal: the output gets no encoder
906
+ * until one elsewhere ends. It is never below what already runs here, so a
907
+ * refusal stops a start and never takes an encoder away.
908
+ *
909
+ * Said out loud when the machine is what bound it, once per change.
910
+ *
911
+ * @param {string} address
912
+ * @param {object[]} live
913
+ * @param {number} perOutput
914
+ * @returns {number}
915
+ */
916
+ #withinMachine(address, live, perOutput) {
917
+ if (!this.admission) {
918
+ return perOutput;
919
+ }
920
+ const machine = this.admission.placesFor(address, live.length);
921
+ const runs = Math.min(perOutput, machine.runs);
922
+ const said = runs < perOutput ? `${runs}:${machine.because}` : "";
923
+ if (said !== (this.#lastMachineBound.get(address) ?? "")) {
924
+ if (said) {
925
+ this.logger.info(
926
+ `encode: ${runs} encoder(s) on ${address} — the whole machine holds no more ` +
927
+ `(${machine.because}; this output alone would be allowed ${perOutput})`
928
+ );
929
+ this.#lastMachineBound.set(address, said);
930
+ } else {
931
+ this.#lastMachineBound.delete(address);
932
+ }
933
+ }
934
+ return runs;
935
+ }
936
+
937
+ /**
938
+ * Take charge of a run this class did not start.
939
+ *
940
+ * The browser asks for a stream and a run begins for it, long before this
941
+ * class has an opinion. Left unknown, that run would be invisible to the plan
942
+ * — which would then start a second encoder over the same numbers, believing
943
+ * nothing was being made there. So whoever starts one hands it over, and from
944
+ * then on it is planned like any other.
945
+ *
946
+ * @param {string} address
947
+ * @param {{ id: string, from: number, to: number, head: number, speedX: number, isAlive: boolean, stop: (because: string) => void }} run
948
+ */
949
+ adopt(address, run) {
950
+ if (!run) {
951
+ return;
952
+ }
953
+ const onThisOutput = this.#runs.get(address) ?? [];
954
+ if (onThisOutput.includes(run)) {
955
+ return;
956
+ }
957
+ onThisOutput.push(run);
958
+ this.#runs.set(address, onThisOutput);
959
+ this.coverageOf(address).claim(run, run.from, endOfRun(run));
960
+ }
961
+
962
+ /**
963
+ * @param {object} run
964
+ * @param {string} because
965
+ */
966
+ #stop(run, because) {
967
+ run.stop(because);
968
+ }
969
+
970
+ /**
971
+ * A run has ended, however it ended. Its stretch goes back to the map — what
972
+ * it finished stays made — and the ending is counted.
973
+ *
974
+ * Wired by whoever builds the run, so that a run built outside this class is
975
+ * still accounted for.
976
+ *
977
+ * @param {import("../encode/EncodeRun.js").RunEnded} ended
978
+ */
979
+ noteEnded(ended) {
980
+ this.#lastState.set(ended.address, ended.run?.state ?? "IDLE");
981
+ if (ended.lastError) {
982
+ this.#lastError.set(ended.address, ended.lastError);
983
+ } else if (ended.because && ended.ending !== ENCODE_EXIT.COMPLETE) {
984
+ this.#lastError.set(ended.address, ended.because);
985
+ }
986
+ const progress = ended.run?.progress?.snapshot?.();
987
+ if (progress) {
988
+ this.#lastProgress.set(ended.address, progress);
989
+ }
990
+ this.#costs.note(ended);
991
+ // Exactly one ending is normal — the run reached the end of the stretch it
992
+ // was given and closed its last file. Every other leaves a piece open, and
993
+ // that piece is under this run's OWN working name, so clearing up after it
994
+ // is a name match: no stretch to search and no bytes to judge. Done for
995
+ // every ending, the normal one included, since a run that finished cleanly
996
+ // has nothing under a working name and the sweep then removes nothing.
997
+ this.#segmentCoverage?.clearUpAfter(ended.address, ended.from);
998
+ this.coverageOf(ended.address).release(ended.run);
999
+ const remaining = this.runsOn(ended.address).filter((run) => run !== ended.run);
1000
+ if (remaining.length === 0) {
1001
+ this.#runs.delete(ended.address);
1002
+ } else {
1003
+ this.#runs.set(ended.address, remaining);
1004
+ }
1005
+ this.#endings.set(ended.ending, (this.#endings.get(ended.ending) ?? 0) + 1);
1006
+ this.#noteInputAvailability(ended);
1007
+ }
1008
+
1009
+ /**
1010
+ * Remember, per output, that its input was not there — and until when nothing
1011
+ * is to be placed on it.
1012
+ *
1013
+ * **Why the plan has to hold this.** A run whose input has gone is not alive,
1014
+ * so the plan sees the stretch it held as free and places another run there at
1015
+ * once — and the next one dies the same way, because nothing about the state
1016
+ * has changed. There WAS a delay for exactly this, doubling from 2 s to 15 s,
1017
+ * and it governed only the dead run's own retry while the plan went on placing
1018
+ * fresh ones beside it. The comment beside that timer predicted this in as
1019
+ * many words and the code did not prevent it. Field 2026-09-12: 2432 ffmpeg
1020
+ * starts in 23 minutes, one every 0.57 s, for 61 minutes, against a delay that
1021
+ * had long since reached its 15 s cap.
1022
+ *
1023
+ * So the delay lives where the decision is taken. It is not a cure for the
1024
+ * input being away — that is the store's claim being withdrawn and the piece
1025
+ * being fetched again — it is what stops one absent input from costing a
1026
+ * thousand processes and a quarter of a million log lines while it is away.
1027
+ *
1028
+ * @param {{ address: string, ending: string }} ended
1029
+ * @returns {void}
1030
+ */
1031
+ #noteInputAvailability(ended) {
1032
+ if (ended.ending !== ENCODE_EXIT.INPUT_LOST) {
1033
+ // CLEARED ONLY BY PROOF THAT THE INPUT WAS THERE, which is a segment
1034
+ // having come out of it. Any other ending was nearly the rule here and is
1035
+ // wrong: at the moment of failure several runs end at once, and one of
1036
+ // them ending `gone` or `stopped` without producing a thing says nothing
1037
+ // about the input — it would have lifted the wait the one beside it had
1038
+ // just set, which is the storm again with an extra step.
1039
+ const produced =
1040
+ ended.firstOutputMs !== null && ended.firstOutputMs !== undefined
1041
+ ? true
1042
+ : Number.isFinite(ended.reached) && Number.isFinite(ended.from) && ended.reached >= ended.from;
1043
+ if (produced) {
1044
+ this.#inputLostAttempts.delete(ended.address);
1045
+ this.#quietUntil.delete(ended.address);
1046
+ }
1047
+ return;
1048
+ }
1049
+ const attempts = (this.#inputLostAttempts.get(ended.address) ?? 0) + 1;
1050
+ this.#inputLostAttempts.set(ended.address, attempts);
1051
+ const delayMs = Math.min(
1052
+ INPUT_QUIET_MAX_MS,
1053
+ INPUT_QUIET_BASE_MS * 2 ** Math.min(attempts - 1, 6)
1054
+ );
1055
+ this.#quietUntil.set(ended.address, this.now() + delayMs);
1056
+ this.logger.info(
1057
+ `encode-plan on ${ended.address}: its input was not there (attempt ${attempts}) — ` +
1058
+ `placing nothing for ${Math.round(delayMs / 1000)}s`
1059
+ );
1060
+ // THE WAKE-UP, because a plan that refuses to act needs something to ask it
1061
+ // again: nothing about the state changes while the data is away, so no event
1062
+ // would arrive to reconsider it.
1063
+ const timer = setTimeout(() => {
1064
+ this.#quietTimers.delete(ended.address);
1065
+ this.planSoon();
1066
+ }, delayMs);
1067
+ timer.unref?.();
1068
+ const previous = this.#quietTimers.get(ended.address);
1069
+ if (previous) {
1070
+ clearTimeout(previous);
1071
+ }
1072
+ this.#quietTimers.set(ended.address, timer);
1073
+ }
1074
+
1075
+ /**
1076
+ * Whether this output is still waiting before anything may be placed on it.
1077
+ *
1078
+ * A boolean rather than the milliseconds left: the figure had one reader and
1079
+ * that reader only asked whether it was above zero, so it was a number
1080
+ * computed and thrown away. How long the wait is was said when it began.
1081
+ *
1082
+ * @param {string} address
1083
+ * @returns {boolean}
1084
+ */
1085
+ #isQuiet(address) {
1086
+ const until = this.#quietUntil.get(address);
1087
+ if (!Number.isFinite(until)) {
1088
+ return false;
1089
+ }
1090
+ if (until - this.now() <= 0) {
1091
+ this.#quietUntil.delete(address);
1092
+ return false;
1093
+ }
1094
+ return true;
1095
+ }
1096
+
1097
+ /**
1098
+ * Forget everything remembered about an output nobody is producing for.
1099
+ *
1100
+ * Three maps are keyed by address, and an output that goes away leaves an
1101
+ * entry in each for the life of the process. Small, and exactly the shape of
1102
+ * accumulation this layer was built to remove from the session.
1103
+ *
1104
+ * @param {string} address
1105
+ * @returns {void}
1106
+ */
1107
+ #forgetInputState(address) {
1108
+ this.#inputLostAttempts.delete(address);
1109
+ this.#quietUntil.delete(address);
1110
+ const timer = this.#quietTimers.get(address);
1111
+ if (timer) {
1112
+ clearTimeout(timer);
1113
+ this.#quietTimers.delete(address);
1114
+ }
1115
+ }
1116
+
1117
+ /**
1118
+ * How runs have ended over the life of this process, by cause.
1119
+ *
1120
+ * The abnormal classes are meant to stand at zero. Without the count,
1121
+ * "we understand why it ended" is indistinguishable from "we noticed it once".
1122
+ *
1123
+ * @returns {Record<string, number>}
1124
+ */
1125
+ endings() {
1126
+ /** @type {Record<string, number>} */
1127
+ const tally = {};
1128
+ for (const ending of Object.values(ENCODE_EXIT)) {
1129
+ tally[ending] = this.#endings.get(ending) ?? 0;
1130
+ }
1131
+ return tally;
1132
+ }
1133
+
1134
+ /**
1135
+ * One line saying what this proxy is encoding and whether anybody is waiting.
1136
+ *
1137
+ * `waiting` is the point of it: a proxy with encoders running and a viewer
1138
+ * still stopped at a segment nobody is making is the failure this layer was
1139
+ * built to remove, and it is visible here rather than inferred from a log.
1140
+ *
1141
+ * @returns {string}
1142
+ */
1143
+ describe() {
1144
+ const parts = [];
1145
+ for (const address of new Set([...this.#demand.addresses(), ...this.#runs.keys()])) {
1146
+ const coverage = this.coverageOf(address);
1147
+ const stated = this.#demand.mapOn(address);
1148
+ const windows = stated.map((zone) => ({ from: zone.from, to: zone.to }));
1149
+ const waiting = firstUnmetWant(coverage, windows);
1150
+ const runs = this.runsOn(address)
1151
+ .map((run) => `#${run.head}..#${run.to}@${run.speedX.toFixed(1)}x`)
1152
+ .join(" ");
1153
+ // The zones as they were stated, with their order, so a plan that is
1154
+ // working at the wrong end of the film is visible rather than inferred.
1155
+ const zones = [...stated]
1156
+ .sort((left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from)
1157
+ .map((w) => `p${w.priority ?? 0}:#${w.from}..#${w.to}`)
1158
+ .join(" ");
1159
+ // THE WHOLE ADDRESS. Cut to sixty characters, every output of one film
1160
+ // printed the same string — the picture, its quality steps and each
1161
+ // soundtrack are told apart only by the tail — so three lines of this
1162
+ // could not be matched to the three things they describe. Read on
1163
+ // 2026-09-07 while accounting for a session that produced nothing, and
1164
+ // the accounting had to be done by which line carried a run.
1165
+ //
1166
+ // And WHAT THE DISK HOLDS beside what is proven closed. They are two
1167
+ // different statements: files with nothing proving them closed reads as a
1168
+ // reporting fault, no files at all reads as an output yet to be made, and
1169
+ // the difference decides where to look.
1170
+ const held = this.#segmentCoverage ? this.#segmentCoverage.filesHeld(address) : -1;
1171
+ // AND WHETHER THE MAP IS BEING SERVED IN ITS OWN ORDER. The zones say
1172
+ // what matters most; this says what the viewer actually waited for, by
1173
+ // band. Waits at `now` are the ones that cost a spinner, and until this
1174
+ // existed there was no figure anywhere saying whether the urgent zone was
1175
+ // served first — the map could have been read backwards and every line
1176
+ // above would have looked the same.
1177
+ const served = this.#describeWaits(address);
1178
+ parts.push(
1179
+ `${address} ready=${coverage.stats().ready}` +
1180
+ `${held < 0 ? "" : ` of ${held} file(s) on disk`} ` +
1181
+ `zones=[${zones}] runs=[${runs}] ` +
1182
+ `waiting=${waiting === null ? "nobody" : `#${waiting}`}` +
1183
+ `${served ? ` served[${served}]` : ""}`
1184
+ );
1185
+ }
1186
+ const tally = this.endings();
1187
+ const endings = Object.entries(tally)
1188
+ .map(([cause, count]) => `${cause}=${count}`)
1189
+ .join(" ");
1190
+ return `encode: ${parts.length === 0 ? "nothing wanted" : parts.join(" | ")} :: endings ${endings}`;
1191
+ }
1192
+ }