@torrent-tv/proxy 2.89.6 → 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 (436) 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 +5 -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/available-share.test.js +76 -76
  258. package/test/background-fill.test.js +190 -190
  259. package/test/client-log-file.test.js +110 -110
  260. package/test/completed-files.test.js +115 -115
  261. package/test/concurrent-cost.test.js +148 -148
  262. package/test/container-media-info.test.js +228 -228
  263. package/test/contention.test.js +76 -76
  264. package/test/core-dumps.test.js +57 -57
  265. package/test/coverage-follows-the-disk.test.js +228 -228
  266. package/test/coverage-map.test.js +195 -195
  267. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  268. package/test/cut-times-timeline.test.js +65 -65
  269. package/test/cuts-follow-published-grid.test.js +109 -109
  270. package/test/data-channel-frame.test.js +63 -63
  271. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  272. package/test/dead-torrent-handle.test.js +52 -52
  273. package/test/declared-rates.test.js +116 -116
  274. package/test/declared-tracks.test.js +43 -43
  275. package/test/decode-cost-fit.test.js +202 -202
  276. package/test/delivery-probe.test.js +393 -393
  277. package/test/demand-register.test.js +206 -206
  278. package/test/dht-bootstrap.test.js +72 -72
  279. package/test/drain-threat.test.js +65 -65
  280. package/test/duplicate-add.test.js +48 -48
  281. package/test/encode-admission.test.js +146 -146
  282. package/test/encode-cost.test.js +275 -275
  283. package/test/encode-exit.test.js +111 -111
  284. package/test/encode-orchestrator.test.js +426 -426
  285. package/test/encode-plan-viewers.test.js +725 -725
  286. package/test/encode-plan.test.js +545 -545
  287. package/test/encode-run-state.test.js +314 -314
  288. package/test/encode-run.test.js +38 -0
  289. package/test/encode-slope.test.js +46 -46
  290. package/test/encoded-output.test.js +39 -39
  291. package/test/encoder-kinds.test.js +122 -122
  292. package/test/encoder-readings.test.js +68 -68
  293. package/test/every-claimant-is-told-its-share.test.js +152 -152
  294. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  295. package/test/failed-start-breaker.test.js +202 -202
  296. package/test/fastest-wires.test.js +143 -143
  297. package/test/ffmpeg-stream-counts.test.js +78 -78
  298. package/test/file-edges.test.js +191 -191
  299. package/test/fixtures/refused-audio-20261002.json +10 -0
  300. package/test/fmp4-presentation-clock.test.js +4 -2
  301. package/test/fmp4-self-contained.test.js +80 -80
  302. package/test/fmp4-timestamps.test.js +140 -140
  303. package/test/fmp4-track-completeness.test.js +41 -41
  304. package/test/health-metrics.test.js +38 -38
  305. package/test/held-request-width.test.js +157 -157
  306. package/test/helpers/encode-run.js +240 -240
  307. package/test/helpers/output-spec.js +63 -63
  308. package/test/host-load.test.js +68 -68
  309. package/test/index-accuracy-is-about-the-file.test.js +128 -128
  310. package/test/init-compat.test.js +219 -219
  311. package/test/input-lost-quiets-the-plan.test.js +261 -261
  312. package/test/input-unavailable.test.js +48 -48
  313. package/test/installation-id.test.js +39 -39
  314. package/test/keeping-period.test.js +83 -83
  315. package/test/keyframe-index-accuracy.test.js +188 -188
  316. package/test/keyframes-belong-to-the-file.test.js +249 -249
  317. package/test/learned-median.test.js +37 -37
  318. package/test/letting-go-asks-who-is-watching.test.js +191 -191
  319. package/test/limit-row-by-area.test.js +60 -60
  320. package/test/link-budget.test.js +111 -111
  321. package/test/link-probe.test.js +56 -56
  322. package/test/local-encoding-data.test.js +273 -273
  323. package/test/logger-repeats.test.js +134 -134
  324. package/test/look-ahead-coverage.test.js +56 -56
  325. package/test/manager-surface.test.js +291 -291
  326. package/test/matroska-cues-track.test.js +192 -192
  327. package/test/media-time.test.js +62 -62
  328. package/test/memory-budget.test.js +390 -390
  329. package/test/move-cost.test.js +216 -216
  330. package/test/mp4-subtitles.test.js +173 -173
  331. package/test/one-authority.test.js +285 -285
  332. package/test/one-budget.test.js +149 -149
  333. package/test/one-resource-divided.test.js +185 -185
  334. package/test/one-serving-output-per-height.test.js +458 -458
  335. package/test/orchestrator-wired.test.js +207 -207
  336. package/test/output-catalog.test.js +39 -39
  337. package/test/output-shape.test.js +21 -21
  338. package/test/output-spec.test.js +251 -251
  339. package/test/output-speed.test.js +87 -87
  340. package/test/outputs-being-prepared.test.js +40 -40
  341. package/test/packet-witness-ring.test.js +236 -236
  342. package/test/packet-witness.test.js +148 -148
  343. package/test/piece-completeness.test.js +37 -1
  344. package/test/piece-disk-store.test.js +401 -401
  345. package/test/piece-from-whole-file.test.js +129 -129
  346. package/test/piece-lru.test.js +319 -319
  347. package/test/piece-reader.test.js +162 -162
  348. package/test/piece-selection-offset.test.js +85 -85
  349. package/test/piece-store-eviction.test.js +595 -595
  350. package/test/piece-store-never-refuses.test.js +153 -153
  351. package/test/piece-store-reservations.test.js +403 -403
  352. package/test/piece-store-slow-disk.test.js +159 -159
  353. package/test/piece-tail.test.js +97 -97
  354. package/test/plan-host-timings.test.js +68 -68
  355. package/test/plan-is-steady.test.js +225 -225
  356. package/test/playback-readiness.test.js +518 -518
  357. package/test/playback-start-regressions.test.js +101 -101
  358. package/test/priority-map-download.test.js +174 -174
  359. package/test/priority-map-emptied.test.js +204 -204
  360. package/test/priority-map-per-output.test.js +215 -215
  361. package/test/priority-map.test.js +163 -163
  362. package/test/probe-wedge-certainty.test.js +60 -60
  363. package/test/produced-copy-choice.test.js +213 -213
  364. package/test/published-timeline.test.js +83 -83
  365. package/test/quality-offer.test.js +160 -160
  366. package/test/rate-control-in-the-output.test.js +180 -180
  367. package/test/read-survives-withdrawal.test.js +164 -164
  368. package/test/read-window.test.js +365 -365
  369. package/test/resume-warm.test.js +39 -39
  370. package/test/run-graph-drift.test.js +37 -37
  371. package/test/run-inputs.test.js +80 -80
  372. package/test/run-intervals.test.js +100 -100
  373. package/test/run-position-follows-published-grid.test.js +89 -89
  374. package/test/run-progress.test.js +64 -64
  375. package/test/same-height-switch.test.js +663 -663
  376. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  377. package/test/seek-landing.test.js +109 -109
  378. package/test/seek-target-not-superseded.test.js +195 -195
  379. package/test/segment-cut-times.test.js +63 -63
  380. package/test/segment-demand.test.js +80 -80
  381. package/test/segment-hold-supersede.test.js +91 -91
  382. package/test/segment-store-eviction.test.js +247 -247
  383. package/test/segment-store.test.js +352 -352
  384. package/test/segment-true-start.test.js +86 -86
  385. package/test/segments-are-shared.test.js +176 -176
  386. package/test/send-chunk-bytes.test.js +86 -86
  387. package/test/serving-output.test.js +102 -102
  388. package/test/shared-piece-store.test.js +310 -310
  389. package/test/sidecar-naming.test.js +142 -142
  390. package/test/soundtrack-rate-bound.test.js +289 -289
  391. package/test/source-file.test.js +133 -133
  392. package/test/source-registry.test.js +18 -18
  393. package/test/split-a-stretch.test.js +139 -139
  394. package/test/stale-request-after-seek.test.js +158 -158
  395. package/test/startup-readings.test.js +124 -124
  396. package/test/stream-route.test.js +237 -237
  397. package/test/subtitle-cue-framing.test.js +200 -200
  398. package/test/subtitle-cue-source.test.js +102 -102
  399. package/test/subtitle-cursor.test.js +63 -63
  400. package/test/subtitle-defaults.test.js +118 -118
  401. package/test/subtitle-language.test.js +252 -252
  402. package/test/supply-margin.test.js +190 -190
  403. package/test/swarm-follows-readers.test.js +174 -174
  404. package/test/swarm-reach.test.js +130 -130
  405. package/test/swarm-selection.test.js +220 -220
  406. package/test/tail-duplication.test.js +167 -167
  407. package/test/the-channel-has-both-ends.test.js +91 -91
  408. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  409. package/test/thread-pool.test.js +53 -53
  410. package/test/timeline.test.js +84 -84
  411. package/test/torrent-contents.test.js +235 -235
  412. package/test/torrent-cost.test.js +71 -71
  413. package/test/torrent-files.test.js +221 -221
  414. package/test/torrent-naming.test.js +255 -255
  415. package/test/tracks-begin-together.test.js +209 -209
  416. package/test/tunnel-renewal.test.js +167 -167
  417. package/test/upload-hurry.test.js +186 -186
  418. package/test/usrsctp-state.test.js +131 -131
  419. package/test/video-facts.test.js +102 -102
  420. package/test/viewer-assignments.test.js +143 -143
  421. package/test/viewer-outputs.test.js +285 -285
  422. package/test/viewer-presence.test.js +116 -116
  423. package/test/viewer-states.test.js +189 -189
  424. package/test/viewer-subtitle-subscription.test.js +96 -96
  425. package/test/viewer.test.js +139 -139
  426. package/test/visible-rung.test.js +37 -37
  427. package/test/wait-ledger.test.js +100 -100
  428. package/test/webrtc-shim.test.js +149 -149
  429. package/test/wedge-certainty.test.js +131 -131
  430. package/test/withdraw-piece-claim.test.js +212 -212
  431. package/test/worker-channel.test.js +158 -158
  432. package/utils/client-log-file.js +151 -151
  433. package/utils/logger.js +312 -312
  434. package/utils/parse-range.js +25 -25
  435. package/utils/perf.js +59 -59
  436. package/utils/torrent-source-key.js +38 -38
@@ -1,1368 +1,1368 @@
1
- /**
2
- * @file How many encoders there should be on one output, and where each of them
3
- * belongs — decided from numbers alone.
4
- *
5
- * The decision is separated from carrying it out on purpose. Every rule below
6
- * was previously a condition somewhere inside an eleven-thousand-line file,
7
- * reachable only by starting a real ffmpeg, and each of them was written for
8
- * one viewer:
9
- *
10
- * - a run was placed at the position of whoever asked, and never at the first
11
- * thing missing, so a viewer moving into a stretch already on disk restarted
12
- * an encoder to make it a second time;
13
- * - a run had no end at all — neither `-to` nor `-t` appeared anywhere — so it
14
- * ran until something killed it, and two runs on one output could not exist
15
- * without writing over each other;
16
- * - nothing stopped a run that had caught up with material somebody else had
17
- * already made.
18
- *
19
- * The rule this file exists to express, stated by the user 2026-09-04:
20
- *
21
- * > Viewers are always independent and always reuse what can be reused. The
22
- * > number of encoders is however many are needed; how many are needed follows
23
- * > from which sets of output parameters are wanted and where the viewers stand
24
- * > inside each. Segments produced by ANY encoder are available to ANY viewer,
25
- * > and which viewer asked never enters the question.
26
- *
27
- * So no name of a viewer reaches this file. It is given what is wanted, what
28
- * exists, what is being made, and what the machine can afford.
29
- *
30
- * **A viewer decides the ORDER the map is walked in and, through the budget, how
31
- * many processes walk it. Nothing else.** Stated by the user 2026-09-05, and it
32
- * is the rule the rest of this file now follows: while a file is being encoded
33
- * it is encoded WHOLE, in the order the map dictates. Who wants which segment
34
- * decides which gap is closed first, never whether a run may go on living.
35
- *
36
- * **A run is therefore never stopped for standing outside a viewer's window.**
37
- * It used to be, and the two decisions that produced that were in direct
38
- * contradiction — measured in the field 2026-09-05 on a viewer watching an
39
- * episode:
40
- *
41
- * 1. this file commanded a start inside the window, at #46;
42
- * 2. `planRunInterval` in the session manager moved the start to #78, because
43
- * it counted a suspended run's claim as reaching `head + look-ahead`;
44
- * 3. this file then saw a run at #78 against a window of [27, 57], found no
45
- * overlap, and killed it as "nothing it was given is wanted";
46
- * 4. neither coverage nor demand had changed, so the same start was commanded
47
- * again — 350-700ms per cycle, dozens of times, no segment ever produced,
48
- * the viewer's picture stopped for 125 seconds.
49
- *
50
- * Both of those other authorities are gone (roadmap item 76, step 5). What is
51
- * left is this file, and the only reasons it stops a run are: nobody is
52
- * watching the output at all; the machine affords fewer processes; or there is
53
- * nothing left unmade anywhere in the track.
54
- *
55
- * **A run's end comes from the coverage**, never from a window: it runs until
56
- * it meets material somebody else has made or is making, or until the end of
57
- * the film.
58
- */
59
-
60
- /**
61
- * One encoder that is running now.
62
- *
63
- * @typedef {object} LiveRun
64
- * @property {string} id
65
- * @property {number} from - The first number it was given.
66
- * @property {number} to - The last number it was given, inclusive.
67
- * @property {number} head - The next number it will produce. Its position.
68
- * @property {number} speedX - The run's processing speed against realtime:
69
- * film made between closed pieces over its own working time
70
- * (`EncodeRun.speedX`), with input waits and stops taken out. Zero or less
71
- * means nothing has measured it yet, and then no comparison involving its
72
- * speed can be made.
73
- */
74
-
75
- /**
76
- * What a viewer is waiting for. Which viewer is deliberately absent.
77
- *
78
- * @typedef {object} WantedSpan
79
- * @property {number} from
80
- * @property {number} to
81
- */
82
-
83
- /**
84
- * @typedef {{ type: "start", from: number, to: number, because: string }
85
- * | { type: "move", run: object, from: number, to: number, because: string }
86
- * | { type: "stop", run: object, because: string }
87
- * | { type: "keep", run: object, from: number, to: number }} PlanAction
88
- */
89
-
90
- /**
91
- * Decide what to do with the encoders on one output.
92
- *
93
- * @param {object} params
94
- * @param {import("./CoverageMap.js").CoverageMap} params.coverage - What has
95
- * been made and what is being made.
96
- * @param {WantedSpan[]} params.windows - What viewers are waiting for, one
97
- * window each. Empty means nobody is watching this output.
98
- * @param {LiveRun[]} params.runs - The encoders running on it now.
99
- * @param {number} params.maxRuns - How many encoders this machine can afford on
100
- * this output. Comes from the same arithmetic that decides the quality offer;
101
- * it is measured per host and never chosen here.
102
- * @param {number} params.segmentSeconds - How much film one segment holds.
103
- * @param {number} [params.killCostSec] - How long stopping an encoder takes,
104
- * measured on this host from its own runs. Zero until something has measured
105
- * it, which makes moving one look cheaper than it is and is said here so the
106
- * bias is known.
107
- * @param {number} [params.now] - The clock, injected. This layer is arithmetic
108
- * and reads no clock of its own; how old a run is is one of its inputs.
109
- * @param {number} [params.firstByteWaitSec] - How long a fresh encoder takes to
110
- * produce anything: process start, opening the input, and the first piece.
111
- * Measured the same way. It replaced a constant of 0.12 s taken from one
112
- * host and charged to every other.
113
- * @param {(others: number) => number} [params.contentionPenaltyFor] - How much
114
- * slower ONE encoder runs with that many others beside it, measured on this
115
- * host. Without it every extra process looks free, and the score then wants an
116
- * encoder per piece: at exactly realtime each next piece is marginally late
117
- * however many are running, so another one always seemed to help a little.
118
- * Unmeasured is 1, and then the budget is the only thing bounding the count.
119
- * @returns {PlanAction[]} Stops first, then moves, then starts, so that a plan
120
- * carried out in order never holds two encoders where it means to hold one.
121
- */
122
- export function planEncoders({
123
- coverage,
124
- windows,
125
- runs,
126
- maxRuns,
127
- segmentSeconds,
128
- killCostSec = 0,
129
- firstByteWaitSec = 0,
130
- now = Date.now(),
131
- refetchSecPerFilmSecond = 0,
132
- contentionPenaltyFor = () => 1,
133
- speedX = 0
134
- }) {
135
- /** @type {PlanAction[]} */
136
- const stops = [];
137
- /** @type {PlanAction[]} */
138
- const moves = [];
139
- /** @type {PlanAction[]} */
140
- const starts = [];
141
- /** @type {PlanAction[]} */
142
- const keeps = [];
143
-
144
- const wanted = Array.isArray(windows) ? windows : [];
145
- const live = Array.isArray(runs) ? runs : [];
146
-
147
- // Nobody is watching this output: every encoder on it is making segments for
148
- // no one. This is the case a look-ahead cannot answer, because look-ahead
149
- // asks how far AHEAD of a viewer a run is and there is no viewer.
150
- if (wanted.length === 0) {
151
- for (const run of live) {
152
- stops.push({ type: "stop", run, because: "nobody is watching this output" });
153
- }
154
- return stops;
155
- }
156
-
157
- const untilNeeded = deadlineReaderFor(wanted, segmentSeconds);
158
- // Segments produced per second, from the fastest measured encoder here.
159
- // Seconds of film per second, divided by the film one piece holds.
160
- //
161
- // A RUN WORKING ON THIS OUTPUT OUTRANKS THE BENCHMARK. The startup figure is
162
- // what this host does on reference clips; a run here is what it does on THIS
163
- // material, and that is the more specific statement. Taken as a floor instead
164
- // — the larger of the two — an encoder reporting half realtime was scored as
165
- // though it ran at twice, and nothing was ever late.
166
- const working = live.reduce((best, run) => Math.max(best, run.speedX || 0), 0);
167
- const rate = segmentSeconds > 0 ? (working > 0 ? working : speedX) / segmentSeconds : 0;
168
- // How long one piece takes AT THE RATE ACTUALLY IN FORCE. Concurrent encoders
169
- // slow each other — measured on this host — so an arrangement's own encoder count
170
- // decides it, and the delays below are computed per arrangement for that
171
- // reason. Taken from the unpenalised rate instead, a piece looked cheaper the
172
- // more encoders there were, which made extra encoders look free: the plan bought a
173
- // second encoder where one served, and the arrivals it was compared on were
174
- // computed at the slower rate all along.
175
- //
176
- // `Infinity` where nothing has been measured, which is what "no speed" means
177
- // and what makes every arrangement equally hopeless rather than equally free.
178
- const pieceAt = (howManyEncoders) => {
179
- const inForce = rate / contentionPenaltyFor(Math.max(0, howManyEncoders - 1));
180
- return inForce > 0 ? 1 / inForce : Number.POSITIVE_INFINITY;
181
- };
182
- // What a encoder costs to take away from where it stands and put somewhere else:
183
- // its death, the start of another, and the wait for the first bytes there.
184
- // Taking an encoder somewhere else is stopping this one and waiting for the
185
- // next to produce. Both halves are measured on this host.
186
- // WHAT A START AND A MOVE OWE BEFORE THE PIECE THEY STAND ON EXISTS, and
187
- // neither is infinite.
188
- //
189
- // The measured `firstByteWaitSec` is spawn to first piece, so it already
190
- // contains one piece's encoding. Separated, because the two scale differently:
191
- // the piece costs more when encoders share the machine, the spawn does not.
192
- //
193
- // spawn overhead = measured first output - what one piece costs alone
194
- // a fresh encoder owes spawn overhead + the piece at the rate in force
195
- // a moved one owes the kill, and then the same
196
- //
197
- // With nothing measured the overhead is zero and a fresh encoder owes exactly
198
- // one piece — which is the honest floor rather than a guess: a piece cannot
199
- // appear before it is encoded, and how fast this host encodes is measured
200
- // before any viewer exists. There was an `Infinity` here for the cost of a
201
- // move, on the reasoning that an unmeasured price must not license an
202
- // irreversible act; it was an exception in a model that needs none, and this
203
- // is the same statement made by arithmetic.
204
- const spawnOverheadSec = Math.max(0, firstByteWaitSec - (rate > 0 ? 1 / rate : 0));
205
- const moveSec = killCostSec + spawnOverheadSec;
206
-
207
- // WHAT A RUN STILL HAS TO GO BEFORE IT PRODUCES ANYTHING — the measured time
208
- // to a first piece, less the time it has already been alive.
209
- //
210
- // This is the memory the score was missing. It is computed afresh whenever
211
- // anything changes, and every arrangement used to be priced as though it were
212
- // the last decision anybody would take: a run that started 10 ms ago was
213
- // assumed to produce instantly, so killing it and starting another looked like
214
- // a straight gain. A move is justified by a benefit that arrives when the
215
- // moved run produces something; taken again before it has, the benefit is
216
- // never collected and the cost is paid twice, three times, forty times.
217
- //
218
- // A run 0.8 s old has 0.14 s left to go against 0.94 s to move it, so it is
219
- // left alone; one working for half a minute has nothing left, and a move
220
- // happens exactly when the film it would reach sooner is worth the restart. No
221
- // state to keep and nothing to choose: one measured figure minus elapsed time.
222
- const finishesItsPieceIn = (run, perPiece) => {
223
- // WHEN THIS RUN FINISHES THE PIECE IT IS STANDING ON.
224
- //
225
- // Two cases and neither is a choice: a run that has produced something is
226
- // working at a known rate, so the piece under it lands within one piece's
227
- // worth of time; a run that has produced nothing is still in its warm-up,
228
- // and what is left of that is the measured time to a first piece less the
229
- // time it has already been alive.
230
- //
231
- // This is the memory the score was missing. It is computed afresh whenever
232
- // anything changes, and each arrangement used to be priced as though it were
233
- // the last decision anybody would take: a run 0.8 s into a 0.9 s piece was
234
- // charged a whole piece for it, the same as one about to start, so killing
235
- // it and beginning again elsewhere looked cheaper by ten milliseconds. A
236
- // move is justified by a benefit that arrives when the moved run produces
237
- // something; taken again before it has, the benefit is never collected and
238
- // the cost is paid twice, three times, forty times.
239
- //
240
- // One measured figure minus elapsed time. Nothing to keep and nothing to
241
- // choose.
242
- if (Number(run.head) !== Number(run.from)) {
243
- return perPiece;
244
- }
245
- const startedAt = Number(run.startedAt);
246
- if (!Number.isFinite(startedAt) || startedAt <= 0) {
247
- return firstByteWaitSec;
248
- }
249
- return Math.max(0, firstByteWaitSec - (now - startedAt) / 1000);
250
- };
251
-
252
- // WHAT EACH BODY OWES BEFORE THE PIECE IT STANDS ON EXISTS, priced at the rate
253
- // the arrangement itself puts in force.
254
- //
255
- // Each encoder states its own debt where it is created, as a function of what one
256
- // piece costs — because only there is it known what the encoder IS, and here only
257
- // how many of them there are. So there is nothing to dispatch on: no kind, no
258
- // tag, no case analysis. The count is known before any debt is needed, which
259
- // is why this is one pass over the encoders rather than a figure computed once
260
- // outside.
261
- const priced = (encoders) => {
262
- const perPiece = pieceAt(encoders.length);
263
- return encoders.map((encoder) => ({ at: encoder.at, delaySec: encoder.owes(perPiece) }));
264
- };
265
-
266
-
267
- // WHERE A SECOND ENCODER MEETS THE ONE ALREADY ON A STRETCH, and whether it is
268
- // worth having.
269
- //
270
- // A stretch of unmade film runs from `from` to `to`. Whoever is already on it
271
- // stands at `from` and owes `w` before the piece under it exists; a fresh one
272
- // placed at `x` owes `d` — its start, and then a whole piece — and both then
273
- // work at the rate two encoders leave each other, which is measured on this
274
- // host and is not half by assumption.
275
- //
276
- // the one already there closes [from, x-1]: w + (x - 1 - from) / r
277
- // the fresh one closes [x, to]: d + (to - x) / r
278
- //
279
- // The first rises with `x` and the second falls, so the stretch is closed
280
- // soonest where they cross:
281
- //
282
- // x* = (from + to + 1) / 2 + (d - w) * r / 2
283
- //
284
- // The midpoint, shifted forward by half the difference of what the two owe,
285
- // expressed in pieces. Halving is the special case `d = w`, which holds when
286
- // both are fresh — and it was applied to every case, including the common one
287
- // where `d` is a start plus a piece and `w` is the tail of a piece already
288
- // being made.
289
- //
290
- // AND WHETHER TO SPLIT AT ALL, which halving never asked. Two encoders under
291
- // contention against one at full speed:
292
- //
293
- // one: w + (to - from - 1) / rate
294
- // two: w + (x* - 1 - from) / r
295
- //
296
- // Nothing back where the second does not win. On the addon host at 1920x1080
297
- // the measured penalty for a second encoder is 1.98 — it takes very nearly
298
- // all of the first's speed — so there a second almost never pays, and it was
299
- // being placed regardless.
300
- const splitAt = (from, to) => {
301
- const pieces = to - from + 1;
302
- if (!(pieces > 1) || !(rate > 0)) {
303
- return null;
304
- }
305
- const together = rate / contentionPenaltyFor(live.length);
306
- if (!(together > 0)) {
307
- return null;
308
- }
309
- const perPieceTogether = 1 / together;
310
- // What the one already on this stretch owes, or a fresh one's debt where
311
- // nobody is on it — and then both sides owe the same and the meeting point
312
- // is the middle, as it should be.
313
- const onIt = live.find((run) => Number(run.head) === from) ?? null;
314
- const owedThere = onIt
315
- ? finishesItsPieceIn(onIt, perPieceTogether)
316
- : firstByteWaitSec + perPieceTogether;
317
- const owedFresh = firstByteWaitSec + perPieceTogether;
318
- const meeting = (from + to + 1) / 2 + ((owedFresh - owedThere) * together) / 2;
319
- const x = Math.min(to, Math.max(from + 1, Math.round(meeting)));
320
- const withTwo = owedThere + (x - 1 - from) * perPieceTogether;
321
- const withOne = owedThere + (pieces - 1) / rate;
322
- return withTwo < withOne ? x : null;
323
- };
324
-
325
- // ------------------------------------------------------------------ WHERE
326
- //
327
- // A question about the FILM, and about nothing else: which numbers are
328
- // missing, when each is needed, how fast this machine encodes, how many
329
- // processes it can hold. No encoder that happens to be running enters it,
330
- // which is why it can be answered by arithmetic.
331
- const positions = placeEncoders({
332
- coverage,
333
- windows: wanted,
334
- howMany: maxRuns,
335
- // EVERY LIVE ENCODER IS PRE-PLACED, because that is what "somebody already
336
- // gets here in time" means. A number one of them reaches before it is
337
- // needed is not a position at all; a number none of them reaches is, and
338
- // needs a encoder brought to it. There is no third case, and in particular no
339
- // separate question of whether an encoder should drive on or be moved:
340
- // driving is simply its arrival, and its arrival is priced in one place.
341
- firstGap: gapFinderFor(coverage, new Set(live), rate, segmentSeconds * refetchSecPerFilmSecond),
342
- deadlineAt: untilNeeded,
343
- splitAt
344
- });
345
-
346
- // -------------------------------------------------------------------- WHO
347
- //
348
- // ARGMIN OF THE OBJECTIVE, EVALUATED. Not a rule that approximates it.
349
- //
350
- // Every way of filling the positions is scored by `latenessOf` and the best is
351
- // taken. There are at most a handful of positions and a handful of encoders, so
352
- // the enumeration is exact: no local rule stands in for the objective, and
353
- // none can therefore disagree with another.
354
- //
355
- // Four such rules were written before this and all four had to go — "place
356
- // where a number is late", "take a encoder that serves nothing", "take one whose
357
- // work is needed later than this", "drive on or move, by cost". Each looked
358
- // like a consequence of the model and each approximated it from a different
359
- // side, so together they contradicted one another and the answer depended on
360
- // which ran first.
361
- /** One decision per live encoder, so none can be decided twice. @type {Map<object, PlanAction>} */
362
- const decided = new Map();
363
- const room = Math.max(0, maxRuns - live.length);
364
- const refetchPerSegment = segmentSeconds * refetchSecPerFilmSecond;
365
-
366
- let arrangements = [{ fill: [], used: new Set(), fresh: 0 }];
367
- for (let index = 0; index < positions.length; index += 1) {
368
- const next = [];
369
- for (const arrangement of arrangements) {
370
- next.push({ fill: [...arrangement.fill, null], used: arrangement.used, fresh: arrangement.fresh });
371
- // A FRESH PROCESS IS OFFERED BEFORE ANY WORKING BODY, so that when the two
372
- // score the same the working one is left alone. Taking it is free in the
373
- // arithmetic — its output stays on disk — but it is not free in fact: the
374
- // run it belongs to has a position, a warm input and a measured speed, and
375
- // all three are thrown away for nothing.
376
- if (arrangement.fresh < room) {
377
- next.push({
378
- fill: [...arrangement.fill, "new"],
379
- used: arrangement.used,
380
- fresh: arrangement.fresh + 1
381
- });
382
- }
383
- for (const run of live) {
384
- if (arrangement.used.has(run)) {
385
- continue;
386
- }
387
- next.push({
388
- fill: [...arrangement.fill, run],
389
- used: new Set([...arrangement.used, run]),
390
- fresh: arrangement.fresh
391
- });
392
- }
393
- }
394
- arrangements = next;
395
- }
396
-
397
- let best = null;
398
- let bestScore = null;
399
- for (const arrangement of arrangements) {
400
- const encoders = [];
401
- for (let index = 0; index < positions.length; index += 1) {
402
- const filler = arrangement.fill[index];
403
- if (filler === null) {
404
- continue;
405
- }
406
- if (filler === "new") {
407
- // A encoder that does not exist yet owes its own start and then the piece.
408
- encoders.push({ at: positions[index], owes: (piece) => spawnOverheadSec + piece });
409
- continue;
410
- }
411
- const head = Number(filler.head);
412
- // Left where it stands it owes what is left of the piece under it; taken
413
- // somewhere else it owes the killing, the start and a whole piece.
414
- encoders.push({
415
- at: positions[index],
416
- owes: head === positions[index]
417
- ? (piece) => finishesItsPieceIn(filler, piece)
418
- : (piece) => moveSec + piece
419
- });
420
- }
421
- // Bodies nobody was given a position for go on working where they stand,
422
- // and their coverage counts: the file is encoded whole.
423
- //
424
- // A encoder given no end pays a restart the moment anybody is placed inside the
425
- // road it would drive: where a run stops is fixed when its process starts,
426
- // so it has to be cut and begun again at its own head. That price was
427
- // invisible here, and an arrangement was scored as free when it was not.
428
- for (const run of live) {
429
- if (arrangement.used.has(run)) {
430
- continue;
431
- }
432
- const head = Number(run.head);
433
- const endless = Number(run.to) < Number(run.from);
434
- const cutInFront = arrangement.fill.some((filler, index) =>
435
- filler !== null && positions[index] > head
436
- && (endless || positions[index] <= Number(run.to)));
437
- encoders.push({
438
- at: head,
439
- owes: cutInFront
440
- ? (piece) => moveSec + piece
441
- : (piece) => finishesItsPieceIn(run, piece)
442
- });
443
- }
444
- const scored = latenessOf(priced(encoders), coverage, wanted, untilNeeded, rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
445
- if (bestScore === null || cheaperThan(scored, bestScore)) {
446
- bestScore = scored;
447
- best = arrangement;
448
- }
449
- }
450
-
451
- // A BODY STANDING ON FILM THAT EXISTS is the one arrangement the enumeration
452
- // above cannot reach: the gap in front of it is nobody's deadline, so it is
453
- // never a position, and the encoder is left to make three hundred pieces a second
454
- // time. Each such encoder is offered its own first gap and the SAME score decides
455
- // — moving costs a restart on everything downstream, staying costs the repeat.
456
- //
457
- // Offered one at a time rather than folded into the enumeration because the
458
- // enumeration is exponential in the number of positions, and this is called
459
- // again on every piece produced. One extra evaluation per encoder against
460
- // several thousand arrangements is the difference between arithmetic and a
461
- // stalled proxy.
462
- const placement = new Map();
463
- for (let index = 0; index < positions.length; index += 1) {
464
- const filler = best ? best.fill[index] : null;
465
- if (filler && filler !== "new") {
466
- placement.set(filler, positions[index]);
467
- }
468
- }
469
- const encodersOf = (override) => {
470
- const encoders = [];
471
- for (const run of live) {
472
- if (override.has(run) && override.get(run) === null) {
473
- // Asked what the film looks like WITHOUT this one.
474
- continue;
475
- }
476
- const at = override.has(run) ? override.get(run) : (placement.get(run) ?? Number(run.head));
477
- const head = Number(run.head);
478
- encoders.push({
479
- at,
480
- owes: at === head
481
- ? (piece) => finishesItsPieceIn(run, piece)
482
- : (piece) => moveSec + piece
483
- });
484
- }
485
- for (let index = 0; index < positions.length; index += 1) {
486
- if ((best ? best.fill[index] : null) === "new") {
487
- encoders.push({ at: positions[index], owes: (piece) => spawnOverheadSec + piece });
488
- }
489
- }
490
- return priced(encoders);
491
- };
492
- const scoreOf = (override) => {
493
- const encoders = encodersOf(override);
494
- return latenessOf(encoders, coverage, wanted, untilNeeded,
495
- rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
496
- };
497
- for (const run of live) {
498
- if (placement.has(run)) {
499
- continue;
500
- }
501
- const gap = coverage.firstGapFrom(run.head, undefined, run);
502
- if (gap === null || gap === Number(run.head)) {
503
- continue;
504
- }
505
- const asIs = scoreOf(new Map());
506
- const moved = scoreOf(new Map([[run, gap]]));
507
- if (cheaperThan(moved, asIs)) {
508
- placement.set(run, gap);
509
- }
510
- }
511
-
512
- /**
513
- * Would the film be worse off without this encoder? Asked of the same score.
514
- *
515
- * @param {object} run
516
- * @returns {boolean}
517
- */
518
- const worseWithout = (run) => {
519
- const kept = encodersOf(new Map());
520
- const without = encodersOf(new Map([[run, null]]));
521
- const scoreOf_ = (encoders) => latenessOf(encoders, coverage, wanted, untilNeeded,
522
- rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
523
- return cheaperThan(scoreOf_(kept), scoreOf_(without));
524
- };
525
-
526
- const stretchAt = (from) => endOfStretch(from, Math.min(
527
- coverage.unmadeRunFrom(from),
528
- coverage.freeRunFrom(from, new Set(live))
529
- ));
530
-
531
- for (let index = 0; index < positions.length; index += 1) {
532
- if ((best ? best.fill[index] : null) !== "new") {
533
- continue;
534
- }
535
- const at = positions[index];
536
- starts.push({
537
- type: "start",
538
- from: at,
539
- to: stretchAt(at),
540
- because: `#${at} is wanted and nobody reaches it in time`
541
- });
542
- }
543
-
544
- for (const run of live) {
545
- const head = Number(run.head);
546
- const at = placement.has(run) ? placement.get(run) : head;
547
- if (at !== head) {
548
- decided.set(run, {
549
- type: "move",
550
- run,
551
- from: at,
552
- to: stretchAt(at),
553
- because: `standing at #${head} scores worse than standing at #${at}, counting ` +
554
- "both how late the film would be and the work that would be done twice"
555
- });
556
- continue;
557
- }
558
- // It stays where it is — unless holding it changes nothing.
559
- //
560
- // A encoder left over from where a viewer used to be goes on costing the
561
- // machine a process while another encoder already reaches everything it
562
- // would. The score says so directly: take it away and see. Removing it is
563
- // refused the moment it makes anything later or leaves film abandoned, so
564
- // this cannot quietly drop the encoder somebody is waiting on.
565
- if (!placement.has(run) && !worseWithout(run)) {
566
- stops.push({
567
- type: "stop",
568
- run,
569
- because: "the film is no worse off without it"
570
- });
571
- continue;
572
- }
573
- decided.set(run, { type: "keep", run, from: head, to: run.to });
574
- }
575
-
576
- // THE MACHINE'S LIMIT BINDS, whatever the map wants. It is measured — the
577
- // processor, the swarm and the piece store each give a figure and the smallest
578
- // wins — and an encoder over it is one the host cannot feed. Which of them
579
- // goes is the same question as any other here: the one the film misses least,
580
- // by the same score.
581
- while (decided.size + starts.length > maxRuns) {
582
- let cheapest = null;
583
- let cheapestScore = null;
584
- for (const [run, action] of decided) {
585
- if (action.type !== "keep") {
586
- continue;
587
- }
588
- const without = latenessOf(encodersOf(new Map([[run, null]])), coverage, wanted, untilNeeded,
589
- rate / contentionPenaltyFor(Math.max(0, live.length - 2)), refetchPerSegment, segmentSeconds);
590
- if (cheapestScore === null || cheaperThan(without, cheapestScore)) {
591
- cheapestScore = without;
592
- cheapest = run;
593
- }
594
- }
595
- if (cheapest === null) {
596
- break;
597
- }
598
- decided.delete(cheapest);
599
- placement.delete(cheapest);
600
- stops.push({
601
- type: "stop",
602
- run: cheapest,
603
- because: `the machine holds ${maxRuns} encoder(s) on this output and this is the one ` +
604
- "the film misses least"
605
- });
606
- }
607
-
608
- for (const action of decided.values()) {
609
- if (action.type === "keep") {
610
- keeps.push(action);
611
- } else {
612
- moves.push(action);
613
- }
614
- }
615
-
616
- // ONE ENCODER'S WORK ENDS WHERE THE NEXT ONE'S BEGINS.
617
- //
618
- // A free stretch may run to the end of the track, and an encoder given all of
619
- // it stands in the road of every encoder placed behind it: they write the
620
- // same names, and each one's output is the other's "material somebody else
621
- // made", so they stop one another. Field 2026-09-05: three encoders started
622
- // on one track within 200 ms, each into the road another was already writing.
623
- // Fifteen readers on a piece store that holds sixteen pieces followed, half
624
- // of all evictions took a piece a reader had declared, and `/stream` began
625
- // handing out bytes that were not the file's.
626
- //
627
- // The bound is taken from the NEXT ENCODER'S START, not from a band edge: a
628
- // band edge travels with the viewer, so every step forward would leave a
629
- // sliver just past the previous encoder and buy an encoder for it.
630
- // A RUN THAT IS STAYING IS IN THE SORT TOO, because its road can be taken.
631
- //
632
- // It used to be left out, on the reading that a run staying put keeps what it
633
- // was given. That is true of the stretch it was GIVEN and false of the road it
634
- // will actually drive: a run with no end carries no `-to` and walks to the end
635
- // of the film, so an encoder placed in front of it writes the same names.
636
- const placed = [...moves, ...starts, ...keeps].sort(
637
- (left, right) => /** @type {any} */ (left).from - /** @type {any} */ (right).from
638
- );
639
- for (let index = 0; index < placed.length - 1; index += 1) {
640
- const here = /** @type {{ type: string, run?: object, from: number, to: number }} */ (placed[index]);
641
- const next = /** @type {{ from: number }} */ (placed[index + 1]);
642
- if (here.to >= 0 && here.to < next.from) {
643
- continue;
644
- }
645
- here.to = next.from - 1;
646
- if (here.type !== "keep") {
647
- continue;
648
- }
649
- // SHORTENING A LIVE RUN'S ROAD MEANS STOPPING IT, not merely writing a
650
- // smaller number down. Where a run's end goes is fixed when its process
651
- // starts, so one that was given none keeps producing past any bound decided
652
- // later and would write one piece into the new encoder's road — two
653
- // processes on one name, which is the collision this whole pass exists to
654
- // prevent. So it ends here and begins again at its own head with a real end;
655
- // the viewer in front pays a restart, which is a cost this file already
656
- // prices rather than a interruption nobody counted.
657
- keeps.splice(keeps.indexOf(here), 1);
658
- moves.push({
659
- type: "move",
660
- run: here.run,
661
- from: here.from,
662
- to: here.to,
663
- because:
664
- `an encoder is needed at #${next.from}, which this run would reach only by ` +
665
- "encoding through; it takes the road up to there and ends by itself"
666
- });
667
- }
668
-
669
- return [...stops, ...moves, ...starts, ...keeps];
670
- }
671
-
672
-
673
-
674
- /**
675
- * THE OBJECTIVE, as a value that can be compared.
676
- *
677
- * THREE COUNTS OF SECONDS, COMPARED IN ORDER. The order is the user's, stated
678
- * 2026-09-06, and a later count decides only where the earlier ones tie:
679
- *
680
- * 1. SECONDS ANYBODY SPENDS LOOKING AT A SPINNER. Nothing outranks it, at any
681
- * size. Walked forward in film order rather than summed piece by piece: a
682
- * viewer who is stopped is not watching, so a wait moves every deadline
683
- * behind it by its own length;
684
- *
685
- * 2. WHEN THE FILM IN FRONT OF THE VIEWERS IS FINISHED — the last piece of it to
686
- * be made, whichever encoder makes it. A stretch no encoder will ever reach
687
- * counts as never, which is what stops the front being abandoned;
688
- *
689
- * 3. WHEN THE WHOLE FILE IS FINISHED — the film behind the viewers included,
690
- * plus what the swarm pays to fetch anything a second time. Film nobody is
691
- * waiting for still has value: a viewer seeking back into a part that exists
692
- * starts playing at once, and seeking back is what people do in the first
693
- * minutes while they find their place. So spare capacity goes to finishing
694
- * the file. This is where "the file is encoded WHOLE" lives; it used to be a
695
- * penalty for film below the lowest encoder, which said the same thing as a
696
- * patch and said it about one edge of the track only.
697
- *
698
- * WHY AN ENCODER MAY STAND BEHIND A VIEWER while film in front is still unmade:
699
- * encoders work at the same time, so one in front and one behind can finish the
700
- * file sooner than two in front. Where nobody is stalled and the front is closed
701
- * just as fast, the file being done sooner is the answer — count 3 deciding a
702
- * tie in 1 and 2, which is exactly what the order is for.
703
- *
704
- * WHY THE COUNTS ARE COMPARED AND NOT ADDED: seconds of somebody waiting and
705
- * seconds until a distant stretch exists are not the same thing, and no measured
706
- * quantity says how many of one are worth one of the other. Adding them would
707
- * mean choosing that exchange rate, which is inventing a number.
708
- *
709
- * @param {{ at: number, delaySec: number }[]} encoders - Where each encoder would
710
- * stand, and how long before it produces anything there: nothing where it is
711
- * already standing, a move or a start otherwise.
712
- * @param {import("./CoverageMap.js").CoverageMap} coverage
713
- * @param {WantedSpan[]} wanted
714
- * @param {(index: number) => number} untilNeeded
715
- * @param {number} rate - Segments per second. Always a real figure: this host
716
- * measures what it encodes at on startup, before any viewer exists, and every
717
- * run that works then refines it. There is no "unmeasured" case to answer.
718
- * @param {number} refetchSecPerSegment
719
- * @param {number} segmentSeconds
720
- * @returns {{ stall: number, ahead: number, whole: number }} Three counts of
721
- * seconds, compared in that order by {@link cheaperThan}.
722
- */
723
- function latenessOf(encoders, coverage, wanted, untilNeeded, rate, refetchSecPerSegment, segmentSeconds) {
724
- const first = Math.min(...wanted.map((span) => span.from));
725
- const last = Math.max(...wanted.map((span) => span.to));
726
- // What a number nobody reaches at all counts as. The film's own length is the
727
- // honest bound — nothing can be later than never — and a finite figure is what
728
- // lets two hopeless arrangements still be told apart by the rest of the sum.
729
- const never = (last + 1) * segmentSeconds;
730
-
731
- // WHICH SIDE OF THE VIEWERS a piece is on. The map states it; nothing here
732
- // works it out from positions, and nothing here knows where a viewer stands.
733
- //
734
- // It was read off the deadline before — no time stated meant behind — and that
735
- // is true only of a viewer who is playing. A paused viewer has no times
736
- // anywhere, so their whole film read as behind them, "ahead before behind"
737
- // had nothing to compare, and the encoder was free to wander to the start of
738
- // the file. Which side a stretch is on and how soon it is wanted are two
739
- // different facts, and the map states both.
740
- // WHAT RANK THE MAP GIVES THIS NUMBER — the highest, where zones overlap,
741
- // because a number two viewers want is wanted as much as the more urgent of
742
- // them wants it.
743
- //
744
- // This replaced a boolean, "is it behind everybody", and the boolean was the
745
- // whole of what the objective knew about the map's own order. The map states
746
- // ten ranks on a film — p100 at the number a viewer is stopped on, doubling
747
- // zones down to p91 for the far tail, p1 for what lies behind them — and all
748
- // of that was collapsed into two buckets and then converted to seconds, where
749
- // "never" for the film behind is the film's own length. On a 48-minute file
750
- // that is 2024 s, which outvotes everything: field 2026-09-08, one viewer got
751
- // three encoders, two of them on film behind them, and the run serving them
752
- // was killed to make room for one.
753
- const rankAt = (at) => {
754
- let rank = 0;
755
- for (const span of wanted) {
756
- if (at >= span.from && at <= span.to) {
757
- rank = Math.max(rank, Number(span.priority) || 0);
758
- }
759
- }
760
- return rank;
761
- };
762
- // The ranks the map actually states, most urgent first. The comparison is over
763
- // these and nothing else, so a rank can never be outvoted by a lower one
764
- // however many seconds are at stake there.
765
- const ranks = [...new Set(wanted.map((span) => Number(span.priority) || 0))]
766
- .sort((left, right) => right - left);
767
-
768
- // EVERY COUNT IS OVER THE FILM, NOT OVER THE ENCODERS. When a piece is made
769
- // depends on which encoder reaches it soonest, and the encoder that reaches
770
- // film in front of the viewers may well be standing behind them.
771
- //
772
- // Counted over the encoders instead — each charged to the side it stands on —
773
- // the score had a hole that swallowed everything: an arrangement with every
774
- // encoder BEHIND the viewers had nothing charged to the film in front, so its
775
- // second term was zero, which is the best value there is. The plan then
776
- // abandoned the film in front of a viewer and put both encoders at the start
777
- // of the file, which is the opposite of the rule it is supposed to obey.
778
- //
779
- // AND THE WAITING IS WALKED FORWARD, not summed piece by piece.
780
- //
781
- // Not a sum of each piece's own lateness. A viewer who is stopped is not
782
- // watching, so everything after the piece they are stopped on is needed that
783
- // much later too: one wait moves every deadline behind it by its own length.
784
- //
785
- // Summed independently instead, the far tail of a long file outvoted the film
786
- // under the viewer's feet — measured, and it placed the only encoder at #114
787
- // while the viewer stood at #100, because thirteen pieces of certain waiting
788
- // "cost" less than 886 distant pieces arriving a little later. Walking the
789
- // clock forward makes that trade impossible: abandoning the near film delays
790
- // the far film by at least as much.
791
- let stalled = 0;
792
- let wastedSwarm = 0;
793
- /** Seconds anybody waits past a deadline, per rank. @type {Map<number, number>} */
794
- const lateAt = new Map(ranks.map((rank) => [rank, 0]));
795
- /** When the last number of a rank is made, per rank. @type {Map<number, number>} */
796
- const doneAt = new Map(ranks.map((rank) => [rank, 0]));
797
- for (let index = first; index <= last; index += 1) {
798
- // Which encoder gets to this piece first, and when. One standing on it is
799
- // already there; one behind it must work its way up, re-making anything
800
- // already made on the way, which costs its own time and the swarm's.
801
- let soonest = Number.POSITIVE_INFINITY;
802
- let byWhom = null;
803
- for (const encoder of encoders) {
804
- if (encoder.at > index) {
805
- continue;
806
- }
807
- // WHEN THIS BODY REACHES THIS NUMBER. `delaySec` is when it finishes the
808
- // piece it is STANDING ON, so the pieces after it are the only ones still
809
- // to be encoded at `rate`.
810
- //
811
- // It used to be `(index - at + 1) / rate` on top of the delay, which
812
- // charges every encoder a whole piece for the one it is already working on. A
813
- // fresh encoder does start from nothing, so for it that is right — and it is
814
- // now inside its own delay. A run 0.8 s into a 0.9 s piece does not, and
815
- // charging it 0.94 s for that piece is what made moving it look cheaper
816
- // than leaving it: from #58 it was priced at 1.89 s to reach #59 against
817
- // 1.88 s for a kill and a cold start, a difference of ten milliseconds
818
- // that is nothing but the double charge. Field 2026-09-08: 39 moves in one
819
- // session, 24 of them between three adjacent numbers, and the picture
820
- // stood still for 116.7 s.
821
- const arrival = encoder.delaySec
822
- + (index - encoder.at) / rate
823
- + coverage.madeBetween(encoder.at, index) * refetchSecPerSegment;
824
- if (arrival < soonest) {
825
- soonest = arrival;
826
- byWhom = encoder;
827
- }
828
- }
829
- if (coverage.isReady(index)) {
830
- // It exists. Nobody waits for it and nothing is owed — but whoever passes
831
- // over it makes it a second time, and the swarm fetches its bytes again.
832
- if (byWhom !== null) {
833
- wastedSwarm += refetchSecPerSegment;
834
- }
835
- continue;
836
- }
837
- // A piece nobody is working towards arrives never. There is no third case:
838
- // the host measures what it encodes at, and what it copies at, before any
839
- // viewer exists, so a speed is always a real number and an arrival can
840
- // always be computed.
841
- // Nothing arrives later than never, which is the bound the film's own length
842
- // gives. It is a definition rather than a guard: it also makes the score
843
- // total on a host whose startup measured nothing at all, where every arrival
844
- // is beyond reckoning and every arrangement is therefore equally hopeless.
845
- const when = byWhom === null ? never : Math.min(soonest, never);
846
- const rank = rankAt(index);
847
- doneAt.set(rank, Math.max(doneAt.get(rank) ?? 0, when));
848
- const deadline = untilNeeded(index);
849
- if (Number.isFinite(deadline)) {
850
- const due = deadline + stalled;
851
- const waited = Math.max(0, when - due);
852
- lateAt.set(rank, (lateAt.get(rank) ?? 0) + waited);
853
- stalled += waited;
854
- }
855
- }
856
-
857
- return {
858
- // THE MAP'S OWN ORDER, AS A VECTOR. One pair per rank the map states, most
859
- // urgent rank first: how long anybody waits at that rank, then when the last
860
- // number of it is made.
861
- //
862
- // Compared position by position, so a rank is never outvoted by a lower one
863
- // — which is the whole of what was asked for: nobody stares at a spinner;
864
- // then the film in front of the viewers is encoded as fast as it can be, band
865
- // by band as the map ranks them; then, with whatever is left over and only
866
- // then, the film behind them, in case somebody seeks back.
867
- //
868
- // No weights, and none possible: a weight would let seconds at one rank buy
869
- // seconds at another, and it would be a number nobody measured. The map is
870
- // the source of truth about what matters, and it already says so.
871
- byRank: ranks.flatMap((rank) => [lateAt.get(rank) ?? 0, doneAt.get(rank) ?? 0]),
872
- // HOW MANY ENCODERS IT TAKES. Ranked below every rank of the map and above
873
- // the swarm's bill, so it cannot buy one where the map is indifferent — and
874
- // the map IS indifferent about spare capacity, which is what bought an
875
- // encoder for film nobody waits for.
876
- encoders: encoders.length,
877
- // WHAT THE SWARM PAYS for anything fetched twice, which delays everything.
878
- wasted: wastedSwarm
879
- };
880
- }
881
-
882
- /**
883
- * Is the first arrangement cheaper than the second?
884
- *
885
- * Three things in order, stated by the user 2026-09-06: nobody stares at a
886
- * spinner; then the film in front of the viewers is finished soonest; then the
887
- * whole file is. A later one decides only where the earlier ones tie.
888
- *
889
- * That order is why an encoder may stand BEHIND a viewer while film in front is
890
- * still unmade: encoders work at the same time, so one in front and one behind
891
- * can finish the file sooner than two in front — and where nobody is stalled and
892
- * the front is closed just as fast, the file being done sooner is the answer.
893
- *
894
- * @param {{ stall: number, ahead: number, whole: number }} left
895
- * @param {{ stall: number, ahead: number, whole: number }} right
896
- * @returns {boolean}
897
- */
898
- function cheaperThan(left, right) {
899
- // POSITION BY POSITION, in the map's own order of ranks. A difference at a
900
- // higher rank settles it, and nothing at a lower one can reopen it.
901
- //
902
- // There is no margin here and there must not be one. A threshold — "a move
903
- // must beat staying by at least what moving costs" — was written while the
904
- // arrival arithmetic charged a run for a piece it had already half made, and
905
- // it was a prop under a comparison that was wrong rather than indifferent.
906
- // With the arithmetic right the two are 1.08 s against 1.88 s, and nothing
907
- // needs propping.
908
- const size = Math.max(left.byRank.length, right.byRank.length);
909
- for (let index = 0; index < size; index += 1) {
910
- const here = left.byRank[index] ?? 0;
911
- const there = right.byRank[index] ?? 0;
912
- if (here !== there) {
913
- return here < there;
914
- }
915
- }
916
- // Where every rank is served identically, fewer encoders. The map is
917
- // indifferent, so the machine decides: a process, a reader of the piece store
918
- // and the swarm's bandwidth are all paid by the viewers the ranks above are
919
- // about.
920
- if (left.encoders !== right.encoders) {
921
- return left.encoders < right.encoders;
922
- }
923
- return left.wasted < right.wasted;
924
- }
925
-
926
- /**
927
- * How long until a number is needed, read off the map.
928
- *
929
- * The map states it per stretch, for the stretch's NEAR EDGE, because a stretch
930
- * is met at its beginning. Every number inside is needed no sooner than that, so
931
- * taking the stretch's figure for all of them is the safe reading: it can only
932
- * make the filling earlier than it has to be, never later.
933
- *
934
- * Where the map says nothing, nobody is coming and nothing can be late.
935
- *
936
- * Inside a stretch the time GROWS with the distance, because a viewer covers a
937
- * second of film in a second: the number `n` places past the near edge is
938
- * reached `n` segments of film later. Taking the near edge's figure for every
939
- * number inside instead makes a whole stretch due at once — measured while
940
- * building this: the first stretch is as wide as the measured allowance, so its
941
- * far end was demanded instantly and an encoder was placed on a number another
942
- * one was already writing.
943
- *
944
- * @param {WantedSpan[]} windows
945
- * @param {number} segmentSeconds - How much film one number holds.
946
- * @returns {(index: number) => number}
947
- */
948
- /** @param {WantedSpan[]} windows */
949
- function firstOf(windows) {
950
- return Math.min(...windows.map((span) => span.from));
951
- }
952
-
953
- /** @param {WantedSpan[]} windows */
954
- function lastOf(windows) {
955
- return Math.max(...windows.map((span) => span.to));
956
- }
957
-
958
- function deadlineReaderFor(windows, segmentSeconds) {
959
- const perSegment = segmentSeconds > 0 ? segmentSeconds : 0;
960
- return (index) => {
961
- let soonest = Number.POSITIVE_INFINITY;
962
- for (const span of windows) {
963
- if (index < span.from || index > span.to) {
964
- continue;
965
- }
966
- const stated = /** @type {{ withinSeconds?: number }} */ (span).withinSeconds;
967
- // A stretch stated with no time is somebody waiting at its near edge: that
968
- // is what stating one means. The rest of it grows with the distance, the
969
- // same as a stated one — read as due all at once instead, a window as wide
970
- // as a viewer's cushion demanded its far end instantly and bought an
971
- // encoder to stand beside one already working.
972
- // `null` IS A STATEMENT AND IT SAYS NOBODY IS COMING. `undefined` is the
973
- // absence of one, and a caller that knows only a position is somebody
974
- // waiting at it.
975
- //
976
- // Read through `Number()`, `null` becomes 0 — due NOW — so the film BEHIND
977
- // the viewers, which the map marks with exactly that, was the most urgent
978
- // material in the file. Everything followed from it: it bought encoders,
979
- // it took the run standing in front of the viewer because that run was the
980
- // nearest encoder to it, and it did so again on every pass. Field 2026-09-08:
981
- // 39 moves in one session, 24 between three adjacent numbers, one viewer
982
- // on three encoders, and the picture stood still for 116.7 s in three
983
- // interruptions, the worst of them 91.8 s.
984
- //
985
- // The map has always said it plainly — `{"from":0,"to":57,"priority":1,
986
- // "withinSeconds":null,"behind":true}` is in the log of every session — and
987
- // this line turned it into its opposite. Fourth time in this repository
988
- // that the input to a calculation was not what the calculation assumed.
989
- const within = stated === undefined ? 0 : (stated === null ? Number.NaN : Number(stated));
990
- if (!Number.isFinite(within)) {
991
- // Stated as no time at all: nobody is coming here.
992
- continue;
993
- }
994
- const here = within + (index - span.from) * perSegment;
995
- if (here < soonest) {
996
- soonest = here;
997
- }
998
- }
999
- return soonest;
1000
- };
1001
- }
1002
-
1003
- /**
1004
- * WHERE ENCODERS BELONG, from the model rather than from a list of cases.
1005
- *
1006
- * The problem this solves, stated exactly:
1007
- *
1008
- * - the track is a line of segment numbers; `M` are the ones not made;
1009
- * - each `x` carries a DEADLINE `D(x)`, the seconds until somebody needs it.
1010
- * That is what the priority map is a reading of — a viewer moving forward
1011
- * covers a second of film in a second, so the time until they are at `x` is
1012
- * the distance to it. `Infinity` where nobody is coming;
1013
- * - an encoder is a SEQUENTIAL producer: placed at `a`, it delivers `a + j` at
1014
- * time `(j + 1) / r`, where `r` is segments per second, measured. It cannot
1015
- * skip, so its whole schedule follows from where it starts;
1016
- * - the machine affords `k` of them, measured.
1017
- *
1018
- * Two consequences fall out and need no rule of their own. Placements
1019
- * `a_1 < ... < a_k` PARTITION the line: encoder `i` is useful only on
1020
- * `[a_i, a_{i+1})`, because past that its neighbour got there first. And a
1021
- * segment served by encoder `i` arrives at `(x - a_i + 1) / r`, which is
1022
- * therefore also the answer to "when would the encoder already placed before it
1023
- * get here" — the second half of the comparison, and the half that was missing.
1024
- *
1025
- * `x` is LATE when it arrives after `D(x)`. The objective is no late segments;
1026
- * where `k` does not stretch to that, lateness beginning as far to the right as
1027
- * possible.
1028
- *
1029
- * THE ALGORITHM is first-fit, left to right:
1030
- *
1031
- * for each missing x with a finite deadline, ascending:
1032
- * if some encoder already placed at a satisfies (x - a + 1)/r <= D(x):
1033
- * it covers x
1034
- * else:
1035
- * place an encoder at x
1036
- *
1037
- * A LIVE run enters as an encoder already placed at its own head. There is no
1038
- * special case for it.
1039
- *
1040
- * WHY IT IS OPTIMAL. The leftmost missing number with a finite deadline must be
1041
- * covered by somebody. An encoder placed exactly on it delivers it at the
1042
- * earliest time any placement can, `1/r`, and covers the longest suffix any
1043
- * placement can — starting further left only re-makes material and arrives
1044
- * later, starting further right does not cover it at all. So the greedy choice
1045
- * is never worse than any other, and the usual exchange argument carries it to
1046
- * the whole line. This is the known result for FIXED-ORDER scheduling with
1047
- * deadlines, where first-fit is optimal at unit processing times, and a segment
1048
- * is one unit. General machine minimisation with release times and deadlines is
1049
- * NP-hard; this case is polynomial because the order is forced and each machine
1050
- * covers a contiguous stretch.
1051
- *
1052
- * WHAT WAS TRIED FIRST AND WAS WRONG, kept because each looked reasonable:
1053
- *
1054
- * - `(h - p) * s / (1 - s)`, how long a run stays in front of a viewer moving
1055
- * forward. It answers a different question: a viewer stopped with an empty
1056
- * buffer needs the segment now, and at exactly realtime that formula says
1057
- * "for ever" while the viewer waits thirteen minutes;
1058
- * - whether a run's head lies inside a wanted band — which ties an encoder to
1059
- * whoever is standing there, and this layer must never know that;
1060
- * - the run's head as a barrier, everything above it placeable. It has no time
1061
- * in it at all, so it cannot tell two segments ahead from two hundred.
1062
- *
1063
- * Each was a case, not a model. The deadline is the model.
1064
- *
1065
- * @param {import("./CoverageMap.js").CoverageMap} coverage
1066
- * @param {Set<object>} surviving - Runs that will still be alive, as encoders
1067
- * already placed at their own heads.
1068
- * @param {number} rate - Segments produced per second by one encoder, measured.
1069
- * Zero when nothing has measured it, and then no arrival time can be computed
1070
- * and every claimed number is left alone.
1071
- * @returns {(at: number, bound: number, deadlineAt: (index: number) => number, alsoPlaced?: number[]) => number | null}
1072
- */
1073
- function gapFinderFor(coverage, surviving, rate, refetchSecPerSegment = 0) {
1074
- /** Encoders already placed: where each stands, and how far its road runs. */
1075
- const placed = [];
1076
- for (const run of surviving) {
1077
- const head = Number(/** @type {{ head?: number }} */ (run).head);
1078
- placed.push({
1079
- at: Number.isFinite(head) ? head : Number(/** @type {{ from: number }} */ (run).from),
1080
- // A live run's road, so that placing inside it can be priced. A run given
1081
- // no end drives to the end of the film, which is what makes the price real.
1082
- // A run given no end drives to the end of the film, which is what makes
1083
- // the price of cutting in front of it real. Written out rather than
1084
- // imported: this file depends on nothing, and that is what lets it be
1085
- // exercised with plain values alone.
1086
- to: Number(/** @type {{ to: number }} */ (run).to) < Number(/** @type {{ from: number }} */ (run).from)
1087
- ? Number.POSITIVE_INFINITY
1088
- : Number(/** @type {{ to: number }} */ (run).to)
1089
- });
1090
- }
1091
- return (at, bound, deadlineAt, alsoPlaced) => {
1092
- const start = Number.isInteger(at) && at > 0 ? at : 0;
1093
- const last = Number.isInteger(bound) ? bound : -1;
1094
- // THE LATE NUMBER THAT IS DUE SOONEST, not the leftmost one.
1095
- //
1096
- // With room for every placement the two are the same answer. With a budget
1097
- // that binds they are not, and the objective decides: lateness pushed as far
1098
- // to the right as possible means the soonest deadline is served first. A
1099
- // walk by number gave the one machine to a viewer due in ten minutes while
1100
- // another stood waiting with an empty buffer.
1101
- //
1102
- // Ties go to the smaller number, so the answer does not depend on the order
1103
- // the map happens to be in.
1104
- let best = null;
1105
- let bestDue = Number.POSITIVE_INFINITY;
1106
- for (let index = start; index <= last; index += 1) {
1107
- if (coverage.isReady(index)) {
1108
- continue;
1109
- }
1110
- const deadline = deadlineAt(index);
1111
- if (!Number.isFinite(deadline)) {
1112
- // NOBODY IS COMING HERE, so nothing can be late — but the film is still
1113
- // wanted, and this is where spare capacity goes. The number is proposed;
1114
- // whether an encoder is actually spent on it is the score's answer, and
1115
- // the score puts anything anybody is waiting for first.
1116
- return index;
1117
- }
1118
- // When would the SOONEST of those already placed get here? Encoders placed
1119
- // EARLIER IN THIS PASS count: the first one placed for a viewer covers the
1120
- // stretch in front of them, and without counting it the walk placed a
1121
- // second and a third on the very next numbers — three processes a segment
1122
- // apart for one person, which is the waste this model exists to refuse.
1123
- let soonest = Number.POSITIVE_INFINITY;
1124
- for (const a of [...placed.map((live) => live.at), ...(alsoPlaced ?? [])]) {
1125
- if (a > index) {
1126
- // Standing past it. Encoders only move forward, so it never will.
1127
- continue;
1128
- }
1129
- if (a === index) {
1130
- // Standing ON it. No placement is faster than the one already made.
1131
- soonest = 0;
1132
- break;
1133
- }
1134
- // WHEN THIS BODY GETS HERE, and both terms of it.
1135
- //
1136
- // Its own encoding of everything between, and the swarm's price for the
1137
- // film it would fetch a SECOND time — every number between that is
1138
- // already made, it makes again. That second term is why "should this
1139
- // encoder drive on or be moved" is not a question of its own: an
1140
- // encoder with three hundred made pieces in front of it is simply slow
1141
- // to arrive, and the model compares arrivals. Asked separately it was a
1142
- // second authority over the same encoder, and the two disagreed.
1143
- const arrival = (index - a + 1) / rate
1144
- + coverage.madeBetween(a, index) * refetchSecPerSegment;
1145
- if (arrival < soonest) {
1146
- soonest = arrival;
1147
- }
1148
- }
1149
- if (soonest <= deadline) {
1150
- // Somebody gets here in time. Nothing to decide.
1151
- continue;
1152
- }
1153
- // IT IS LATE, AND THAT IS ALL THIS DECIDES. Whether filling it is worth
1154
- // the price is not asked here: this only proposes candidates, and the
1155
- // score decides how many of them are taken and by whom. Asked here as
1156
- // well, it was a second cost model beside the objective — with its own
1157
- // idea of what a process costs — and the two disagreed at exactly
1158
- // realtime, where every next piece is marginally late and each looked
1159
- // worth its own encoder.
1160
- if (deadline < bestDue) {
1161
- best = index;
1162
- bestDue = deadline;
1163
- }
1164
- }
1165
- return best;
1166
- };
1167
- }
1168
-
1169
- /**
1170
- * The last number of a stretch that begins at `from` and is `length` long.
1171
- *
1172
- * `-1` when the length is not finite, which is this layer's word for a run with
1173
- * no end: the film's length is not known, so there is nothing to stop it at, and
1174
- * a number invented here would be an end nobody measured.
1175
- *
1176
- * @param {number} from
1177
- * @param {number} length
1178
- * @returns {number}
1179
- */
1180
- function endOfStretch(from, length) {
1181
- return Number.isFinite(length) ? from + Math.max(1, length) - 1 : -1;
1182
- }
1183
-
1184
- /**
1185
- * The lowest number a viewer is waiting for that is not ready — what the plan
1186
- * is judged by.
1187
- *
1188
- * Not used to decide anything: it is the figure a log line carries, so that a
1189
- * plan that keeps producing while a viewer waits is visible rather than
1190
- * inferred.
1191
- *
1192
- * @param {import("./CoverageMap.js").CoverageMap} coverage
1193
- * @param {WantedSpan[]} windows
1194
- * @returns {number | null}
1195
- */
1196
- export function firstUnmetWant(coverage, windows) {
1197
- let lowest = null;
1198
- for (const span of windows ?? []) {
1199
- for (let at = span.from; at <= span.to; at += 1) {
1200
- if (!coverage.isReady(at)) {
1201
- if (lowest === null || at < lowest) {
1202
- lowest = at;
1203
- }
1204
- break;
1205
- }
1206
- }
1207
- }
1208
- return lowest;
1209
- }
1210
-
1211
- /**
1212
- * Where to put the encoders this machine can afford.
1213
- *
1214
- * Two things are wanted of a division of the film, and they are wanted in this
1215
- * order:
1216
- *
1217
- * 1. **the viewer must not stop.** An encoder starting at `q` stays ahead of a
1218
- * viewer at `p` while `y / s <= q + y - p`, so it holds `(q - p) * s / (1-s)`
1219
- * of film and no more. Beyond that the viewer catches it, and the next
1220
- * encoder has to be standing there. That is where the first ones go, and it
1221
- * is why the stretches grow: the further off one starts, the later the
1222
- * viewer arrives and the longer it may work;
1223
- * 2. **the film should be finished as soon as possible.** Once the viewer is
1224
- * safe, whatever is left is divided EQUALLY between the encoders that
1225
- * remain: equal shares finish together, and any other division finishes when
1226
- * its longest share does. That is what makes seeking cheap — the film exists.
1227
- *
1228
- * At or above realtime the first requirement is met by one encoder for the
1229
- * whole film, and every other encoder goes to the second — which is the common
1230
- * case on a copied picture, and is why "one viewer, one encoder" was never the
1231
- * rule.
1232
- *
1233
- * @param {object} params
1234
- * @param {import("./CoverageMap.js").CoverageMap} params.coverage
1235
- * @param {WantedSpan[]} params.windows - The merged map, in this output's own
1236
- * numbering. Its highest-numbered band starts where the viewer is.
1237
- * @param {number} params.howMany - What the machine affords.
1238
- * @param {number} params.speedX - Measured. Zero when nothing has measured it,
1239
- * and then only the first requirement can be served.
1240
- * @param {(at: number, bound: number, deadlineAt: (index: number) => number, placed: number[]) => number | null} [params.firstGap] -
1241
- * Where a gap may be opened. Defaults to the map's own answer; the plan hands
1242
- * in one that also counts a number a live run has claimed but will not reach
1243
- * before it is needed, which is the only way anybody beyond a working encoder
1244
- * is served.
1245
- * @param {(index: number) => number} [params.deadlineAt] - Seconds until that
1246
- * number is needed. `Infinity` where nobody is coming. Absent means every
1247
- * stated want is due now.
1248
- * @returns {number[]} Where to start each encoder, ascending.
1249
- */
1250
- export function placeEncoders({
1251
- coverage,
1252
- windows,
1253
- howMany,
1254
- firstGap = null,
1255
- deadlineAt = null,
1256
- // WHERE TWO ENCODERS SHARE A STRETCH, and whether a second is worth having at
1257
- // all. Derived by whoever holds the measurements — the rates, the contention
1258
- // penalty, what a start costs — because this function is positional and holds
1259
- // none of them. The default is the midpoint, which IS the answer when both are
1260
- // fresh and owe the same, and is what a caller with nothing measured falls
1261
- // back on.
1262
- splitAt = (from, to) => from + Math.floor((to - from + 1) / 2)
1263
- }) {
1264
- if (!(howMany > 0) || windows.length === 0) {
1265
- return [];
1266
- }
1267
- // NOW when the caller says nothing. A stated want with no time is somebody
1268
- // waiting on it — that is what stating one means — so the honest reading is
1269
- // that it is due. `Infinity` is a statement in its own right and has to be
1270
- // made: it says nobody is coming.
1271
- const untilNeeded = deadlineAt ?? (() => 0);
1272
- /** Where this pass has placed so far — each one covers what it can reach. */
1273
- const placedHere = [];
1274
- const gapAt = firstGap
1275
- ? (at, bound) => firstGap(at, bound, untilNeeded, placedHere)
1276
- : (at, bound) => coverage.firstGapFrom(at, bound);
1277
-
1278
-
1279
- // CANDIDATES COME FROM THE PRIORITY MAP, IN THE ORDER THE MAP STATES.
1280
- //
1281
- // The map already answers every question that was being re-derived here. Its
1282
- // ranks say what matters most — the number a viewer is stopped on, then what
1283
- // is in front of them band by band, then the rest of the track, and last of
1284
- // all what lies behind them. A pause flattens those ranks; a seek moves them;
1285
- // a second viewer merges into them. So walking the map in its own order is
1286
- // what "ahead before behind" means, and nothing here has to work out where the
1287
- // viewers are.
1288
- //
1289
- // It was not read that way. This walked the film by number and proposed
1290
- // whatever was late, then a second pass divided the leftovers — an order of
1291
- // its own invention, which put the beginning of the file before the film in
1292
- // front of a viewer and, at one point, proposed #0, #1 and #2 as three
1293
- // separate places.
1294
- //
1295
- // One candidate per zone: the first number in it nobody has and nobody
1296
- // reaches in time. Zones with no deadline can have nothing late in them, so
1297
- // there it is simply the first number nobody has — which is how spare capacity
1298
- // comes to finish the file.
1299
- /** @type {number[]} */
1300
- const places = [];
1301
- const byRank = [...windows].sort(
1302
- (left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from
1303
- );
1304
- for (const zone of byRank) {
1305
- if (places.length >= howMany) {
1306
- break;
1307
- }
1308
- const at = gapAt(zone.from, zone.to);
1309
- if (at === null || places.includes(at)) {
1310
- continue;
1311
- }
1312
- places.push(at);
1313
- placedHere.push(at);
1314
- }
1315
-
1316
- // AND WHERE TO SPLIT WHAT IS LEFT, for the capacity the map has not spent.
1317
- //
1318
- // The search above proposes only what is LATE, so once one encoder covers a
1319
- // zone in time that zone proposes nothing more — and a machine that holds four
1320
- // ran one. Finishing a contiguous stretch soonest with several machines of the
1321
- // same speed means dividing it between them, which is where these come from:
1322
- // the widest run of film between two encoders, split.
1323
- //
1324
- // Proposing is not spending. The score decides whether another process is
1325
- // worth it, and its first term — how late the film is — always outranks its
1326
- // second, so this can never take capacity from somebody waiting.
1327
- while (places.length < howMany) {
1328
- const edges = [...places].sort((left, right) => left - right);
1329
- let widestFrom = null;
1330
- let widest = 0;
1331
- for (let index = 0; index <= edges.length; index += 1) {
1332
- const from = index === 0 ? firstOf(windows) : edges[index - 1] + 1;
1333
- const to = index === edges.length ? lastOf(windows) : edges[index] - 1;
1334
- const room_ = coverage.unmadeRunFrom(from);
1335
- if (to >= from && room_ > widest) {
1336
- // WHERE THE TWO OF THEM MEET, calculated rather than halved. Halving is
1337
- // the answer only when both encoders are fresh and owe the same, and it
1338
- // was applied to every case — one already working is partway through a
1339
- // piece while a new one owes its whole start, so the point where they
1340
- // finish together lies further on. Nothing back means a second encoder
1341
- // does not pay for itself here at all: two under this host's measured
1342
- // contention against one at full speed, a comparison halving never made.
1343
- const meet = splitAt(from, Math.min(from + room_ - 1, to));
1344
- if (meet !== null) {
1345
- widest = room_;
1346
- widestFrom = meet;
1347
- }
1348
- }
1349
- }
1350
- if (widestFrom === null) {
1351
- break;
1352
- }
1353
- const at = coverage.firstGapFrom(widestFrom, lastOf(windows));
1354
- if (at === null || places.includes(at)) {
1355
- break;
1356
- }
1357
- places.push(at);
1358
- placedHere.push(at);
1359
- }
1360
-
1361
- // These are CANDIDATES, not decisions. What is late proposes first, because
1362
- // that is what a viewer feels; what is merely unmade proposes after it. The
1363
- // score decides which of them are worth a process, and a paused viewer, who
1364
- // states no deadline at all, therefore still leaves the file being finished
1365
- // rather than the machine falling idle.
1366
- return places.sort((left, right) => left - right);
1367
- }
1368
-
1
+ /**
2
+ * @file How many encoders there should be on one output, and where each of them
3
+ * belongs — decided from numbers alone.
4
+ *
5
+ * The decision is separated from carrying it out on purpose. Every rule below
6
+ * was previously a condition somewhere inside an eleven-thousand-line file,
7
+ * reachable only by starting a real ffmpeg, and each of them was written for
8
+ * one viewer:
9
+ *
10
+ * - a run was placed at the position of whoever asked, and never at the first
11
+ * thing missing, so a viewer moving into a stretch already on disk restarted
12
+ * an encoder to make it a second time;
13
+ * - a run had no end at all — neither `-to` nor `-t` appeared anywhere — so it
14
+ * ran until something killed it, and two runs on one output could not exist
15
+ * without writing over each other;
16
+ * - nothing stopped a run that had caught up with material somebody else had
17
+ * already made.
18
+ *
19
+ * The rule this file exists to express, stated by the user 2026-09-04:
20
+ *
21
+ * > Viewers are always independent and always reuse what can be reused. The
22
+ * > number of encoders is however many are needed; how many are needed follows
23
+ * > from which sets of output parameters are wanted and where the viewers stand
24
+ * > inside each. Segments produced by ANY encoder are available to ANY viewer,
25
+ * > and which viewer asked never enters the question.
26
+ *
27
+ * So no name of a viewer reaches this file. It is given what is wanted, what
28
+ * exists, what is being made, and what the machine can afford.
29
+ *
30
+ * **A viewer decides the ORDER the map is walked in and, through the budget, how
31
+ * many processes walk it. Nothing else.** Stated by the user 2026-09-05, and it
32
+ * is the rule the rest of this file now follows: while a file is being encoded
33
+ * it is encoded WHOLE, in the order the map dictates. Who wants which segment
34
+ * decides which gap is closed first, never whether a run may go on living.
35
+ *
36
+ * **A run is therefore never stopped for standing outside a viewer's window.**
37
+ * It used to be, and the two decisions that produced that were in direct
38
+ * contradiction — measured in the field 2026-09-05 on a viewer watching an
39
+ * episode:
40
+ *
41
+ * 1. this file commanded a start inside the window, at #46;
42
+ * 2. `planRunInterval` in the session manager moved the start to #78, because
43
+ * it counted a suspended run's claim as reaching `head + look-ahead`;
44
+ * 3. this file then saw a run at #78 against a window of [27, 57], found no
45
+ * overlap, and killed it as "nothing it was given is wanted";
46
+ * 4. neither coverage nor demand had changed, so the same start was commanded
47
+ * again — 350-700ms per cycle, dozens of times, no segment ever produced,
48
+ * the viewer's picture stopped for 125 seconds.
49
+ *
50
+ * Both of those other authorities are gone (roadmap item 76, step 5). What is
51
+ * left is this file, and the only reasons it stops a run are: nobody is
52
+ * watching the output at all; the machine affords fewer processes; or there is
53
+ * nothing left unmade anywhere in the track.
54
+ *
55
+ * **A run's end comes from the coverage**, never from a window: it runs until
56
+ * it meets material somebody else has made or is making, or until the end of
57
+ * the film.
58
+ */
59
+
60
+ /**
61
+ * One encoder that is running now.
62
+ *
63
+ * @typedef {object} LiveRun
64
+ * @property {string} id
65
+ * @property {number} from - The first number it was given.
66
+ * @property {number} to - The last number it was given, inclusive.
67
+ * @property {number} head - The next number it will produce. Its position.
68
+ * @property {number} speedX - The run's processing speed against realtime:
69
+ * film made between closed pieces over its own working time
70
+ * (`EncodeRun.speedX`), with input waits and stops taken out. Zero or less
71
+ * means nothing has measured it yet, and then no comparison involving its
72
+ * speed can be made.
73
+ */
74
+
75
+ /**
76
+ * What a viewer is waiting for. Which viewer is deliberately absent.
77
+ *
78
+ * @typedef {object} WantedSpan
79
+ * @property {number} from
80
+ * @property {number} to
81
+ */
82
+
83
+ /**
84
+ * @typedef {{ type: "start", from: number, to: number, because: string }
85
+ * | { type: "move", run: object, from: number, to: number, because: string }
86
+ * | { type: "stop", run: object, because: string }
87
+ * | { type: "keep", run: object, from: number, to: number }} PlanAction
88
+ */
89
+
90
+ /**
91
+ * Decide what to do with the encoders on one output.
92
+ *
93
+ * @param {object} params
94
+ * @param {import("./CoverageMap.js").CoverageMap} params.coverage - What has
95
+ * been made and what is being made.
96
+ * @param {WantedSpan[]} params.windows - What viewers are waiting for, one
97
+ * window each. Empty means nobody is watching this output.
98
+ * @param {LiveRun[]} params.runs - The encoders running on it now.
99
+ * @param {number} params.maxRuns - How many encoders this machine can afford on
100
+ * this output. Comes from the same arithmetic that decides the quality offer;
101
+ * it is measured per host and never chosen here.
102
+ * @param {number} params.segmentSeconds - How much film one segment holds.
103
+ * @param {number} [params.killCostSec] - How long stopping an encoder takes,
104
+ * measured on this host from its own runs. Zero until something has measured
105
+ * it, which makes moving one look cheaper than it is and is said here so the
106
+ * bias is known.
107
+ * @param {number} [params.now] - The clock, injected. This layer is arithmetic
108
+ * and reads no clock of its own; how old a run is is one of its inputs.
109
+ * @param {number} [params.firstByteWaitSec] - How long a fresh encoder takes to
110
+ * produce anything: process start, opening the input, and the first piece.
111
+ * Measured the same way. It replaced a constant of 0.12 s taken from one
112
+ * host and charged to every other.
113
+ * @param {(others: number) => number} [params.contentionPenaltyFor] - How much
114
+ * slower ONE encoder runs with that many others beside it, measured on this
115
+ * host. Without it every extra process looks free, and the score then wants an
116
+ * encoder per piece: at exactly realtime each next piece is marginally late
117
+ * however many are running, so another one always seemed to help a little.
118
+ * Unmeasured is 1, and then the budget is the only thing bounding the count.
119
+ * @returns {PlanAction[]} Stops first, then moves, then starts, so that a plan
120
+ * carried out in order never holds two encoders where it means to hold one.
121
+ */
122
+ export function planEncoders({
123
+ coverage,
124
+ windows,
125
+ runs,
126
+ maxRuns,
127
+ segmentSeconds,
128
+ killCostSec = 0,
129
+ firstByteWaitSec = 0,
130
+ now = Date.now(),
131
+ refetchSecPerFilmSecond = 0,
132
+ contentionPenaltyFor = () => 1,
133
+ speedX = 0
134
+ }) {
135
+ /** @type {PlanAction[]} */
136
+ const stops = [];
137
+ /** @type {PlanAction[]} */
138
+ const moves = [];
139
+ /** @type {PlanAction[]} */
140
+ const starts = [];
141
+ /** @type {PlanAction[]} */
142
+ const keeps = [];
143
+
144
+ const wanted = Array.isArray(windows) ? windows : [];
145
+ const live = Array.isArray(runs) ? runs : [];
146
+
147
+ // Nobody is watching this output: every encoder on it is making segments for
148
+ // no one. This is the case a look-ahead cannot answer, because look-ahead
149
+ // asks how far AHEAD of a viewer a run is and there is no viewer.
150
+ if (wanted.length === 0) {
151
+ for (const run of live) {
152
+ stops.push({ type: "stop", run, because: "nobody is watching this output" });
153
+ }
154
+ return stops;
155
+ }
156
+
157
+ const untilNeeded = deadlineReaderFor(wanted, segmentSeconds);
158
+ // Segments produced per second, from the fastest measured encoder here.
159
+ // Seconds of film per second, divided by the film one piece holds.
160
+ //
161
+ // A RUN WORKING ON THIS OUTPUT OUTRANKS THE BENCHMARK. The startup figure is
162
+ // what this host does on reference clips; a run here is what it does on THIS
163
+ // material, and that is the more specific statement. Taken as a floor instead
164
+ // — the larger of the two — an encoder reporting half realtime was scored as
165
+ // though it ran at twice, and nothing was ever late.
166
+ const working = live.reduce((best, run) => Math.max(best, run.speedX || 0), 0);
167
+ const rate = segmentSeconds > 0 ? (working > 0 ? working : speedX) / segmentSeconds : 0;
168
+ // How long one piece takes AT THE RATE ACTUALLY IN FORCE. Concurrent encoders
169
+ // slow each other — measured on this host — so an arrangement's own encoder count
170
+ // decides it, and the delays below are computed per arrangement for that
171
+ // reason. Taken from the unpenalised rate instead, a piece looked cheaper the
172
+ // more encoders there were, which made extra encoders look free: the plan bought a
173
+ // second encoder where one served, and the arrivals it was compared on were
174
+ // computed at the slower rate all along.
175
+ //
176
+ // `Infinity` where nothing has been measured, which is what "no speed" means
177
+ // and what makes every arrangement equally hopeless rather than equally free.
178
+ const pieceAt = (howManyEncoders) => {
179
+ const inForce = rate / contentionPenaltyFor(Math.max(0, howManyEncoders - 1));
180
+ return inForce > 0 ? 1 / inForce : Number.POSITIVE_INFINITY;
181
+ };
182
+ // What a encoder costs to take away from where it stands and put somewhere else:
183
+ // its death, the start of another, and the wait for the first bytes there.
184
+ // Taking an encoder somewhere else is stopping this one and waiting for the
185
+ // next to produce. Both halves are measured on this host.
186
+ // WHAT A START AND A MOVE OWE BEFORE THE PIECE THEY STAND ON EXISTS, and
187
+ // neither is infinite.
188
+ //
189
+ // The measured `firstByteWaitSec` is spawn to first piece, so it already
190
+ // contains one piece's encoding. Separated, because the two scale differently:
191
+ // the piece costs more when encoders share the machine, the spawn does not.
192
+ //
193
+ // spawn overhead = measured first output - what one piece costs alone
194
+ // a fresh encoder owes spawn overhead + the piece at the rate in force
195
+ // a moved one owes the kill, and then the same
196
+ //
197
+ // With nothing measured the overhead is zero and a fresh encoder owes exactly
198
+ // one piece — which is the honest floor rather than a guess: a piece cannot
199
+ // appear before it is encoded, and how fast this host encodes is measured
200
+ // before any viewer exists. There was an `Infinity` here for the cost of a
201
+ // move, on the reasoning that an unmeasured price must not license an
202
+ // irreversible act; it was an exception in a model that needs none, and this
203
+ // is the same statement made by arithmetic.
204
+ const spawnOverheadSec = Math.max(0, firstByteWaitSec - (rate > 0 ? 1 / rate : 0));
205
+ const moveSec = killCostSec + spawnOverheadSec;
206
+
207
+ // WHAT A RUN STILL HAS TO GO BEFORE IT PRODUCES ANYTHING — the measured time
208
+ // to a first piece, less the time it has already been alive.
209
+ //
210
+ // This is the memory the score was missing. It is computed afresh whenever
211
+ // anything changes, and every arrangement used to be priced as though it were
212
+ // the last decision anybody would take: a run that started 10 ms ago was
213
+ // assumed to produce instantly, so killing it and starting another looked like
214
+ // a straight gain. A move is justified by a benefit that arrives when the
215
+ // moved run produces something; taken again before it has, the benefit is
216
+ // never collected and the cost is paid twice, three times, forty times.
217
+ //
218
+ // A run 0.8 s old has 0.14 s left to go against 0.94 s to move it, so it is
219
+ // left alone; one working for half a minute has nothing left, and a move
220
+ // happens exactly when the film it would reach sooner is worth the restart. No
221
+ // state to keep and nothing to choose: one measured figure minus elapsed time.
222
+ const finishesItsPieceIn = (run, perPiece) => {
223
+ // WHEN THIS RUN FINISHES THE PIECE IT IS STANDING ON.
224
+ //
225
+ // Two cases and neither is a choice: a run that has produced something is
226
+ // working at a known rate, so the piece under it lands within one piece's
227
+ // worth of time; a run that has produced nothing is still in its warm-up,
228
+ // and what is left of that is the measured time to a first piece less the
229
+ // time it has already been alive.
230
+ //
231
+ // This is the memory the score was missing. It is computed afresh whenever
232
+ // anything changes, and each arrangement used to be priced as though it were
233
+ // the last decision anybody would take: a run 0.8 s into a 0.9 s piece was
234
+ // charged a whole piece for it, the same as one about to start, so killing
235
+ // it and beginning again elsewhere looked cheaper by ten milliseconds. A
236
+ // move is justified by a benefit that arrives when the moved run produces
237
+ // something; taken again before it has, the benefit is never collected and
238
+ // the cost is paid twice, three times, forty times.
239
+ //
240
+ // One measured figure minus elapsed time. Nothing to keep and nothing to
241
+ // choose.
242
+ if (Number(run.head) !== Number(run.from)) {
243
+ return perPiece;
244
+ }
245
+ const startedAt = Number(run.startedAt);
246
+ if (!Number.isFinite(startedAt) || startedAt <= 0) {
247
+ return firstByteWaitSec;
248
+ }
249
+ return Math.max(0, firstByteWaitSec - (now - startedAt) / 1000);
250
+ };
251
+
252
+ // WHAT EACH BODY OWES BEFORE THE PIECE IT STANDS ON EXISTS, priced at the rate
253
+ // the arrangement itself puts in force.
254
+ //
255
+ // Each encoder states its own debt where it is created, as a function of what one
256
+ // piece costs — because only there is it known what the encoder IS, and here only
257
+ // how many of them there are. So there is nothing to dispatch on: no kind, no
258
+ // tag, no case analysis. The count is known before any debt is needed, which
259
+ // is why this is one pass over the encoders rather than a figure computed once
260
+ // outside.
261
+ const priced = (encoders) => {
262
+ const perPiece = pieceAt(encoders.length);
263
+ return encoders.map((encoder) => ({ at: encoder.at, delaySec: encoder.owes(perPiece) }));
264
+ };
265
+
266
+
267
+ // WHERE A SECOND ENCODER MEETS THE ONE ALREADY ON A STRETCH, and whether it is
268
+ // worth having.
269
+ //
270
+ // A stretch of unmade film runs from `from` to `to`. Whoever is already on it
271
+ // stands at `from` and owes `w` before the piece under it exists; a fresh one
272
+ // placed at `x` owes `d` — its start, and then a whole piece — and both then
273
+ // work at the rate two encoders leave each other, which is measured on this
274
+ // host and is not half by assumption.
275
+ //
276
+ // the one already there closes [from, x-1]: w + (x - 1 - from) / r
277
+ // the fresh one closes [x, to]: d + (to - x) / r
278
+ //
279
+ // The first rises with `x` and the second falls, so the stretch is closed
280
+ // soonest where they cross:
281
+ //
282
+ // x* = (from + to + 1) / 2 + (d - w) * r / 2
283
+ //
284
+ // The midpoint, shifted forward by half the difference of what the two owe,
285
+ // expressed in pieces. Halving is the special case `d = w`, which holds when
286
+ // both are fresh — and it was applied to every case, including the common one
287
+ // where `d` is a start plus a piece and `w` is the tail of a piece already
288
+ // being made.
289
+ //
290
+ // AND WHETHER TO SPLIT AT ALL, which halving never asked. Two encoders under
291
+ // contention against one at full speed:
292
+ //
293
+ // one: w + (to - from - 1) / rate
294
+ // two: w + (x* - 1 - from) / r
295
+ //
296
+ // Nothing back where the second does not win. On the addon host at 1920x1080
297
+ // the measured penalty for a second encoder is 1.98 — it takes very nearly
298
+ // all of the first's speed — so there a second almost never pays, and it was
299
+ // being placed regardless.
300
+ const splitAt = (from, to) => {
301
+ const pieces = to - from + 1;
302
+ if (!(pieces > 1) || !(rate > 0)) {
303
+ return null;
304
+ }
305
+ const together = rate / contentionPenaltyFor(live.length);
306
+ if (!(together > 0)) {
307
+ return null;
308
+ }
309
+ const perPieceTogether = 1 / together;
310
+ // What the one already on this stretch owes, or a fresh one's debt where
311
+ // nobody is on it — and then both sides owe the same and the meeting point
312
+ // is the middle, as it should be.
313
+ const onIt = live.find((run) => Number(run.head) === from) ?? null;
314
+ const owedThere = onIt
315
+ ? finishesItsPieceIn(onIt, perPieceTogether)
316
+ : firstByteWaitSec + perPieceTogether;
317
+ const owedFresh = firstByteWaitSec + perPieceTogether;
318
+ const meeting = (from + to + 1) / 2 + ((owedFresh - owedThere) * together) / 2;
319
+ const x = Math.min(to, Math.max(from + 1, Math.round(meeting)));
320
+ const withTwo = owedThere + (x - 1 - from) * perPieceTogether;
321
+ const withOne = owedThere + (pieces - 1) / rate;
322
+ return withTwo < withOne ? x : null;
323
+ };
324
+
325
+ // ------------------------------------------------------------------ WHERE
326
+ //
327
+ // A question about the FILM, and about nothing else: which numbers are
328
+ // missing, when each is needed, how fast this machine encodes, how many
329
+ // processes it can hold. No encoder that happens to be running enters it,
330
+ // which is why it can be answered by arithmetic.
331
+ const positions = placeEncoders({
332
+ coverage,
333
+ windows: wanted,
334
+ howMany: maxRuns,
335
+ // EVERY LIVE ENCODER IS PRE-PLACED, because that is what "somebody already
336
+ // gets here in time" means. A number one of them reaches before it is
337
+ // needed is not a position at all; a number none of them reaches is, and
338
+ // needs a encoder brought to it. There is no third case, and in particular no
339
+ // separate question of whether an encoder should drive on or be moved:
340
+ // driving is simply its arrival, and its arrival is priced in one place.
341
+ firstGap: gapFinderFor(coverage, new Set(live), rate, segmentSeconds * refetchSecPerFilmSecond),
342
+ deadlineAt: untilNeeded,
343
+ splitAt
344
+ });
345
+
346
+ // -------------------------------------------------------------------- WHO
347
+ //
348
+ // ARGMIN OF THE OBJECTIVE, EVALUATED. Not a rule that approximates it.
349
+ //
350
+ // Every way of filling the positions is scored by `latenessOf` and the best is
351
+ // taken. There are at most a handful of positions and a handful of encoders, so
352
+ // the enumeration is exact: no local rule stands in for the objective, and
353
+ // none can therefore disagree with another.
354
+ //
355
+ // Four such rules were written before this and all four had to go — "place
356
+ // where a number is late", "take a encoder that serves nothing", "take one whose
357
+ // work is needed later than this", "drive on or move, by cost". Each looked
358
+ // like a consequence of the model and each approximated it from a different
359
+ // side, so together they contradicted one another and the answer depended on
360
+ // which ran first.
361
+ /** One decision per live encoder, so none can be decided twice. @type {Map<object, PlanAction>} */
362
+ const decided = new Map();
363
+ const room = Math.max(0, maxRuns - live.length);
364
+ const refetchPerSegment = segmentSeconds * refetchSecPerFilmSecond;
365
+
366
+ let arrangements = [{ fill: [], used: new Set(), fresh: 0 }];
367
+ for (let index = 0; index < positions.length; index += 1) {
368
+ const next = [];
369
+ for (const arrangement of arrangements) {
370
+ next.push({ fill: [...arrangement.fill, null], used: arrangement.used, fresh: arrangement.fresh });
371
+ // A FRESH PROCESS IS OFFERED BEFORE ANY WORKING BODY, so that when the two
372
+ // score the same the working one is left alone. Taking it is free in the
373
+ // arithmetic — its output stays on disk — but it is not free in fact: the
374
+ // run it belongs to has a position, a warm input and a measured speed, and
375
+ // all three are thrown away for nothing.
376
+ if (arrangement.fresh < room) {
377
+ next.push({
378
+ fill: [...arrangement.fill, "new"],
379
+ used: arrangement.used,
380
+ fresh: arrangement.fresh + 1
381
+ });
382
+ }
383
+ for (const run of live) {
384
+ if (arrangement.used.has(run)) {
385
+ continue;
386
+ }
387
+ next.push({
388
+ fill: [...arrangement.fill, run],
389
+ used: new Set([...arrangement.used, run]),
390
+ fresh: arrangement.fresh
391
+ });
392
+ }
393
+ }
394
+ arrangements = next;
395
+ }
396
+
397
+ let best = null;
398
+ let bestScore = null;
399
+ for (const arrangement of arrangements) {
400
+ const encoders = [];
401
+ for (let index = 0; index < positions.length; index += 1) {
402
+ const filler = arrangement.fill[index];
403
+ if (filler === null) {
404
+ continue;
405
+ }
406
+ if (filler === "new") {
407
+ // A encoder that does not exist yet owes its own start and then the piece.
408
+ encoders.push({ at: positions[index], owes: (piece) => spawnOverheadSec + piece });
409
+ continue;
410
+ }
411
+ const head = Number(filler.head);
412
+ // Left where it stands it owes what is left of the piece under it; taken
413
+ // somewhere else it owes the killing, the start and a whole piece.
414
+ encoders.push({
415
+ at: positions[index],
416
+ owes: head === positions[index]
417
+ ? (piece) => finishesItsPieceIn(filler, piece)
418
+ : (piece) => moveSec + piece
419
+ });
420
+ }
421
+ // Bodies nobody was given a position for go on working where they stand,
422
+ // and their coverage counts: the file is encoded whole.
423
+ //
424
+ // A encoder given no end pays a restart the moment anybody is placed inside the
425
+ // road it would drive: where a run stops is fixed when its process starts,
426
+ // so it has to be cut and begun again at its own head. That price was
427
+ // invisible here, and an arrangement was scored as free when it was not.
428
+ for (const run of live) {
429
+ if (arrangement.used.has(run)) {
430
+ continue;
431
+ }
432
+ const head = Number(run.head);
433
+ const endless = Number(run.to) < Number(run.from);
434
+ const cutInFront = arrangement.fill.some((filler, index) =>
435
+ filler !== null && positions[index] > head
436
+ && (endless || positions[index] <= Number(run.to)));
437
+ encoders.push({
438
+ at: head,
439
+ owes: cutInFront
440
+ ? (piece) => moveSec + piece
441
+ : (piece) => finishesItsPieceIn(run, piece)
442
+ });
443
+ }
444
+ const scored = latenessOf(priced(encoders), coverage, wanted, untilNeeded, rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
445
+ if (bestScore === null || cheaperThan(scored, bestScore)) {
446
+ bestScore = scored;
447
+ best = arrangement;
448
+ }
449
+ }
450
+
451
+ // A BODY STANDING ON FILM THAT EXISTS is the one arrangement the enumeration
452
+ // above cannot reach: the gap in front of it is nobody's deadline, so it is
453
+ // never a position, and the encoder is left to make three hundred pieces a second
454
+ // time. Each such encoder is offered its own first gap and the SAME score decides
455
+ // — moving costs a restart on everything downstream, staying costs the repeat.
456
+ //
457
+ // Offered one at a time rather than folded into the enumeration because the
458
+ // enumeration is exponential in the number of positions, and this is called
459
+ // again on every piece produced. One extra evaluation per encoder against
460
+ // several thousand arrangements is the difference between arithmetic and a
461
+ // stalled proxy.
462
+ const placement = new Map();
463
+ for (let index = 0; index < positions.length; index += 1) {
464
+ const filler = best ? best.fill[index] : null;
465
+ if (filler && filler !== "new") {
466
+ placement.set(filler, positions[index]);
467
+ }
468
+ }
469
+ const encodersOf = (override) => {
470
+ const encoders = [];
471
+ for (const run of live) {
472
+ if (override.has(run) && override.get(run) === null) {
473
+ // Asked what the film looks like WITHOUT this one.
474
+ continue;
475
+ }
476
+ const at = override.has(run) ? override.get(run) : (placement.get(run) ?? Number(run.head));
477
+ const head = Number(run.head);
478
+ encoders.push({
479
+ at,
480
+ owes: at === head
481
+ ? (piece) => finishesItsPieceIn(run, piece)
482
+ : (piece) => moveSec + piece
483
+ });
484
+ }
485
+ for (let index = 0; index < positions.length; index += 1) {
486
+ if ((best ? best.fill[index] : null) === "new") {
487
+ encoders.push({ at: positions[index], owes: (piece) => spawnOverheadSec + piece });
488
+ }
489
+ }
490
+ return priced(encoders);
491
+ };
492
+ const scoreOf = (override) => {
493
+ const encoders = encodersOf(override);
494
+ return latenessOf(encoders, coverage, wanted, untilNeeded,
495
+ rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
496
+ };
497
+ for (const run of live) {
498
+ if (placement.has(run)) {
499
+ continue;
500
+ }
501
+ const gap = coverage.firstGapFrom(run.head, undefined, run);
502
+ if (gap === null || gap === Number(run.head)) {
503
+ continue;
504
+ }
505
+ const asIs = scoreOf(new Map());
506
+ const moved = scoreOf(new Map([[run, gap]]));
507
+ if (cheaperThan(moved, asIs)) {
508
+ placement.set(run, gap);
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Would the film be worse off without this encoder? Asked of the same score.
514
+ *
515
+ * @param {object} run
516
+ * @returns {boolean}
517
+ */
518
+ const worseWithout = (run) => {
519
+ const kept = encodersOf(new Map());
520
+ const without = encodersOf(new Map([[run, null]]));
521
+ const scoreOf_ = (encoders) => latenessOf(encoders, coverage, wanted, untilNeeded,
522
+ rate / contentionPenaltyFor(Math.max(0, encoders.length - 1)), refetchPerSegment, segmentSeconds);
523
+ return cheaperThan(scoreOf_(kept), scoreOf_(without));
524
+ };
525
+
526
+ const stretchAt = (from) => endOfStretch(from, Math.min(
527
+ coverage.unmadeRunFrom(from),
528
+ coverage.freeRunFrom(from, new Set(live))
529
+ ));
530
+
531
+ for (let index = 0; index < positions.length; index += 1) {
532
+ if ((best ? best.fill[index] : null) !== "new") {
533
+ continue;
534
+ }
535
+ const at = positions[index];
536
+ starts.push({
537
+ type: "start",
538
+ from: at,
539
+ to: stretchAt(at),
540
+ because: `#${at} is wanted and nobody reaches it in time`
541
+ });
542
+ }
543
+
544
+ for (const run of live) {
545
+ const head = Number(run.head);
546
+ const at = placement.has(run) ? placement.get(run) : head;
547
+ if (at !== head) {
548
+ decided.set(run, {
549
+ type: "move",
550
+ run,
551
+ from: at,
552
+ to: stretchAt(at),
553
+ because: `standing at #${head} scores worse than standing at #${at}, counting ` +
554
+ "both how late the film would be and the work that would be done twice"
555
+ });
556
+ continue;
557
+ }
558
+ // It stays where it is — unless holding it changes nothing.
559
+ //
560
+ // A encoder left over from where a viewer used to be goes on costing the
561
+ // machine a process while another encoder already reaches everything it
562
+ // would. The score says so directly: take it away and see. Removing it is
563
+ // refused the moment it makes anything later or leaves film abandoned, so
564
+ // this cannot quietly drop the encoder somebody is waiting on.
565
+ if (!placement.has(run) && !worseWithout(run)) {
566
+ stops.push({
567
+ type: "stop",
568
+ run,
569
+ because: "the film is no worse off without it"
570
+ });
571
+ continue;
572
+ }
573
+ decided.set(run, { type: "keep", run, from: head, to: run.to });
574
+ }
575
+
576
+ // THE MACHINE'S LIMIT BINDS, whatever the map wants. It is measured — the
577
+ // processor, the swarm and the piece store each give a figure and the smallest
578
+ // wins — and an encoder over it is one the host cannot feed. Which of them
579
+ // goes is the same question as any other here: the one the film misses least,
580
+ // by the same score.
581
+ while (decided.size + starts.length > maxRuns) {
582
+ let cheapest = null;
583
+ let cheapestScore = null;
584
+ for (const [run, action] of decided) {
585
+ if (action.type !== "keep") {
586
+ continue;
587
+ }
588
+ const without = latenessOf(encodersOf(new Map([[run, null]])), coverage, wanted, untilNeeded,
589
+ rate / contentionPenaltyFor(Math.max(0, live.length - 2)), refetchPerSegment, segmentSeconds);
590
+ if (cheapestScore === null || cheaperThan(without, cheapestScore)) {
591
+ cheapestScore = without;
592
+ cheapest = run;
593
+ }
594
+ }
595
+ if (cheapest === null) {
596
+ break;
597
+ }
598
+ decided.delete(cheapest);
599
+ placement.delete(cheapest);
600
+ stops.push({
601
+ type: "stop",
602
+ run: cheapest,
603
+ because: `the machine holds ${maxRuns} encoder(s) on this output and this is the one ` +
604
+ "the film misses least"
605
+ });
606
+ }
607
+
608
+ for (const action of decided.values()) {
609
+ if (action.type === "keep") {
610
+ keeps.push(action);
611
+ } else {
612
+ moves.push(action);
613
+ }
614
+ }
615
+
616
+ // ONE ENCODER'S WORK ENDS WHERE THE NEXT ONE'S BEGINS.
617
+ //
618
+ // A free stretch may run to the end of the track, and an encoder given all of
619
+ // it stands in the road of every encoder placed behind it: they write the
620
+ // same names, and each one's output is the other's "material somebody else
621
+ // made", so they stop one another. Field 2026-09-05: three encoders started
622
+ // on one track within 200 ms, each into the road another was already writing.
623
+ // Fifteen readers on a piece store that holds sixteen pieces followed, half
624
+ // of all evictions took a piece a reader had declared, and `/stream` began
625
+ // handing out bytes that were not the file's.
626
+ //
627
+ // The bound is taken from the NEXT ENCODER'S START, not from a band edge: a
628
+ // band edge travels with the viewer, so every step forward would leave a
629
+ // sliver just past the previous encoder and buy an encoder for it.
630
+ // A RUN THAT IS STAYING IS IN THE SORT TOO, because its road can be taken.
631
+ //
632
+ // It used to be left out, on the reading that a run staying put keeps what it
633
+ // was given. That is true of the stretch it was GIVEN and false of the road it
634
+ // will actually drive: a run with no end carries no `-to` and walks to the end
635
+ // of the film, so an encoder placed in front of it writes the same names.
636
+ const placed = [...moves, ...starts, ...keeps].sort(
637
+ (left, right) => /** @type {any} */ (left).from - /** @type {any} */ (right).from
638
+ );
639
+ for (let index = 0; index < placed.length - 1; index += 1) {
640
+ const here = /** @type {{ type: string, run?: object, from: number, to: number }} */ (placed[index]);
641
+ const next = /** @type {{ from: number }} */ (placed[index + 1]);
642
+ if (here.to >= 0 && here.to < next.from) {
643
+ continue;
644
+ }
645
+ here.to = next.from - 1;
646
+ if (here.type !== "keep") {
647
+ continue;
648
+ }
649
+ // SHORTENING A LIVE RUN'S ROAD MEANS STOPPING IT, not merely writing a
650
+ // smaller number down. Where a run's end goes is fixed when its process
651
+ // starts, so one that was given none keeps producing past any bound decided
652
+ // later and would write one piece into the new encoder's road — two
653
+ // processes on one name, which is the collision this whole pass exists to
654
+ // prevent. So it ends here and begins again at its own head with a real end;
655
+ // the viewer in front pays a restart, which is a cost this file already
656
+ // prices rather than a interruption nobody counted.
657
+ keeps.splice(keeps.indexOf(here), 1);
658
+ moves.push({
659
+ type: "move",
660
+ run: here.run,
661
+ from: here.from,
662
+ to: here.to,
663
+ because:
664
+ `an encoder is needed at #${next.from}, which this run would reach only by ` +
665
+ "encoding through; it takes the road up to there and ends by itself"
666
+ });
667
+ }
668
+
669
+ return [...stops, ...moves, ...starts, ...keeps];
670
+ }
671
+
672
+
673
+
674
+ /**
675
+ * THE OBJECTIVE, as a value that can be compared.
676
+ *
677
+ * THREE COUNTS OF SECONDS, COMPARED IN ORDER. The order is the user's, stated
678
+ * 2026-09-06, and a later count decides only where the earlier ones tie:
679
+ *
680
+ * 1. SECONDS ANYBODY SPENDS LOOKING AT A SPINNER. Nothing outranks it, at any
681
+ * size. Walked forward in film order rather than summed piece by piece: a
682
+ * viewer who is stopped is not watching, so a wait moves every deadline
683
+ * behind it by its own length;
684
+ *
685
+ * 2. WHEN THE FILM IN FRONT OF THE VIEWERS IS FINISHED — the last piece of it to
686
+ * be made, whichever encoder makes it. A stretch no encoder will ever reach
687
+ * counts as never, which is what stops the front being abandoned;
688
+ *
689
+ * 3. WHEN THE WHOLE FILE IS FINISHED — the film behind the viewers included,
690
+ * plus what the swarm pays to fetch anything a second time. Film nobody is
691
+ * waiting for still has value: a viewer seeking back into a part that exists
692
+ * starts playing at once, and seeking back is what people do in the first
693
+ * minutes while they find their place. So spare capacity goes to finishing
694
+ * the file. This is where "the file is encoded WHOLE" lives; it used to be a
695
+ * penalty for film below the lowest encoder, which said the same thing as a
696
+ * patch and said it about one edge of the track only.
697
+ *
698
+ * WHY AN ENCODER MAY STAND BEHIND A VIEWER while film in front is still unmade:
699
+ * encoders work at the same time, so one in front and one behind can finish the
700
+ * file sooner than two in front. Where nobody is stalled and the front is closed
701
+ * just as fast, the file being done sooner is the answer — count 3 deciding a
702
+ * tie in 1 and 2, which is exactly what the order is for.
703
+ *
704
+ * WHY THE COUNTS ARE COMPARED AND NOT ADDED: seconds of somebody waiting and
705
+ * seconds until a distant stretch exists are not the same thing, and no measured
706
+ * quantity says how many of one are worth one of the other. Adding them would
707
+ * mean choosing that exchange rate, which is inventing a number.
708
+ *
709
+ * @param {{ at: number, delaySec: number }[]} encoders - Where each encoder would
710
+ * stand, and how long before it produces anything there: nothing where it is
711
+ * already standing, a move or a start otherwise.
712
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
713
+ * @param {WantedSpan[]} wanted
714
+ * @param {(index: number) => number} untilNeeded
715
+ * @param {number} rate - Segments per second. Always a real figure: this host
716
+ * measures what it encodes at on startup, before any viewer exists, and every
717
+ * run that works then refines it. There is no "unmeasured" case to answer.
718
+ * @param {number} refetchSecPerSegment
719
+ * @param {number} segmentSeconds
720
+ * @returns {{ stall: number, ahead: number, whole: number }} Three counts of
721
+ * seconds, compared in that order by {@link cheaperThan}.
722
+ */
723
+ function latenessOf(encoders, coverage, wanted, untilNeeded, rate, refetchSecPerSegment, segmentSeconds) {
724
+ const first = Math.min(...wanted.map((span) => span.from));
725
+ const last = Math.max(...wanted.map((span) => span.to));
726
+ // What a number nobody reaches at all counts as. The film's own length is the
727
+ // honest bound — nothing can be later than never — and a finite figure is what
728
+ // lets two hopeless arrangements still be told apart by the rest of the sum.
729
+ const never = (last + 1) * segmentSeconds;
730
+
731
+ // WHICH SIDE OF THE VIEWERS a piece is on. The map states it; nothing here
732
+ // works it out from positions, and nothing here knows where a viewer stands.
733
+ //
734
+ // It was read off the deadline before — no time stated meant behind — and that
735
+ // is true only of a viewer who is playing. A paused viewer has no times
736
+ // anywhere, so their whole film read as behind them, "ahead before behind"
737
+ // had nothing to compare, and the encoder was free to wander to the start of
738
+ // the file. Which side a stretch is on and how soon it is wanted are two
739
+ // different facts, and the map states both.
740
+ // WHAT RANK THE MAP GIVES THIS NUMBER — the highest, where zones overlap,
741
+ // because a number two viewers want is wanted as much as the more urgent of
742
+ // them wants it.
743
+ //
744
+ // This replaced a boolean, "is it behind everybody", and the boolean was the
745
+ // whole of what the objective knew about the map's own order. The map states
746
+ // ten ranks on a film — p100 at the number a viewer is stopped on, doubling
747
+ // zones down to p91 for the far tail, p1 for what lies behind them — and all
748
+ // of that was collapsed into two buckets and then converted to seconds, where
749
+ // "never" for the film behind is the film's own length. On a 48-minute file
750
+ // that is 2024 s, which outvotes everything: field 2026-09-08, one viewer got
751
+ // three encoders, two of them on film behind them, and the run serving them
752
+ // was killed to make room for one.
753
+ const rankAt = (at) => {
754
+ let rank = 0;
755
+ for (const span of wanted) {
756
+ if (at >= span.from && at <= span.to) {
757
+ rank = Math.max(rank, Number(span.priority) || 0);
758
+ }
759
+ }
760
+ return rank;
761
+ };
762
+ // The ranks the map actually states, most urgent first. The comparison is over
763
+ // these and nothing else, so a rank can never be outvoted by a lower one
764
+ // however many seconds are at stake there.
765
+ const ranks = [...new Set(wanted.map((span) => Number(span.priority) || 0))]
766
+ .sort((left, right) => right - left);
767
+
768
+ // EVERY COUNT IS OVER THE FILM, NOT OVER THE ENCODERS. When a piece is made
769
+ // depends on which encoder reaches it soonest, and the encoder that reaches
770
+ // film in front of the viewers may well be standing behind them.
771
+ //
772
+ // Counted over the encoders instead — each charged to the side it stands on —
773
+ // the score had a hole that swallowed everything: an arrangement with every
774
+ // encoder BEHIND the viewers had nothing charged to the film in front, so its
775
+ // second term was zero, which is the best value there is. The plan then
776
+ // abandoned the film in front of a viewer and put both encoders at the start
777
+ // of the file, which is the opposite of the rule it is supposed to obey.
778
+ //
779
+ // AND THE WAITING IS WALKED FORWARD, not summed piece by piece.
780
+ //
781
+ // Not a sum of each piece's own lateness. A viewer who is stopped is not
782
+ // watching, so everything after the piece they are stopped on is needed that
783
+ // much later too: one wait moves every deadline behind it by its own length.
784
+ //
785
+ // Summed independently instead, the far tail of a long file outvoted the film
786
+ // under the viewer's feet — measured, and it placed the only encoder at #114
787
+ // while the viewer stood at #100, because thirteen pieces of certain waiting
788
+ // "cost" less than 886 distant pieces arriving a little later. Walking the
789
+ // clock forward makes that trade impossible: abandoning the near film delays
790
+ // the far film by at least as much.
791
+ let stalled = 0;
792
+ let wastedSwarm = 0;
793
+ /** Seconds anybody waits past a deadline, per rank. @type {Map<number, number>} */
794
+ const lateAt = new Map(ranks.map((rank) => [rank, 0]));
795
+ /** When the last number of a rank is made, per rank. @type {Map<number, number>} */
796
+ const doneAt = new Map(ranks.map((rank) => [rank, 0]));
797
+ for (let index = first; index <= last; index += 1) {
798
+ // Which encoder gets to this piece first, and when. One standing on it is
799
+ // already there; one behind it must work its way up, re-making anything
800
+ // already made on the way, which costs its own time and the swarm's.
801
+ let soonest = Number.POSITIVE_INFINITY;
802
+ let byWhom = null;
803
+ for (const encoder of encoders) {
804
+ if (encoder.at > index) {
805
+ continue;
806
+ }
807
+ // WHEN THIS BODY REACHES THIS NUMBER. `delaySec` is when it finishes the
808
+ // piece it is STANDING ON, so the pieces after it are the only ones still
809
+ // to be encoded at `rate`.
810
+ //
811
+ // It used to be `(index - at + 1) / rate` on top of the delay, which
812
+ // charges every encoder a whole piece for the one it is already working on. A
813
+ // fresh encoder does start from nothing, so for it that is right — and it is
814
+ // now inside its own delay. A run 0.8 s into a 0.9 s piece does not, and
815
+ // charging it 0.94 s for that piece is what made moving it look cheaper
816
+ // than leaving it: from #58 it was priced at 1.89 s to reach #59 against
817
+ // 1.88 s for a kill and a cold start, a difference of ten milliseconds
818
+ // that is nothing but the double charge. Field 2026-09-08: 39 moves in one
819
+ // session, 24 of them between three adjacent numbers, and the picture
820
+ // stood still for 116.7 s.
821
+ const arrival = encoder.delaySec
822
+ + (index - encoder.at) / rate
823
+ + coverage.madeBetween(encoder.at, index) * refetchSecPerSegment;
824
+ if (arrival < soonest) {
825
+ soonest = arrival;
826
+ byWhom = encoder;
827
+ }
828
+ }
829
+ if (coverage.isReady(index)) {
830
+ // It exists. Nobody waits for it and nothing is owed — but whoever passes
831
+ // over it makes it a second time, and the swarm fetches its bytes again.
832
+ if (byWhom !== null) {
833
+ wastedSwarm += refetchSecPerSegment;
834
+ }
835
+ continue;
836
+ }
837
+ // A piece nobody is working towards arrives never. There is no third case:
838
+ // the host measures what it encodes at, and what it copies at, before any
839
+ // viewer exists, so a speed is always a real number and an arrival can
840
+ // always be computed.
841
+ // Nothing arrives later than never, which is the bound the film's own length
842
+ // gives. It is a definition rather than a guard: it also makes the score
843
+ // total on a host whose startup measured nothing at all, where every arrival
844
+ // is beyond reckoning and every arrangement is therefore equally hopeless.
845
+ const when = byWhom === null ? never : Math.min(soonest, never);
846
+ const rank = rankAt(index);
847
+ doneAt.set(rank, Math.max(doneAt.get(rank) ?? 0, when));
848
+ const deadline = untilNeeded(index);
849
+ if (Number.isFinite(deadline)) {
850
+ const due = deadline + stalled;
851
+ const waited = Math.max(0, when - due);
852
+ lateAt.set(rank, (lateAt.get(rank) ?? 0) + waited);
853
+ stalled += waited;
854
+ }
855
+ }
856
+
857
+ return {
858
+ // THE MAP'S OWN ORDER, AS A VECTOR. One pair per rank the map states, most
859
+ // urgent rank first: how long anybody waits at that rank, then when the last
860
+ // number of it is made.
861
+ //
862
+ // Compared position by position, so a rank is never outvoted by a lower one
863
+ // — which is the whole of what was asked for: nobody stares at a spinner;
864
+ // then the film in front of the viewers is encoded as fast as it can be, band
865
+ // by band as the map ranks them; then, with whatever is left over and only
866
+ // then, the film behind them, in case somebody seeks back.
867
+ //
868
+ // No weights, and none possible: a weight would let seconds at one rank buy
869
+ // seconds at another, and it would be a number nobody measured. The map is
870
+ // the source of truth about what matters, and it already says so.
871
+ byRank: ranks.flatMap((rank) => [lateAt.get(rank) ?? 0, doneAt.get(rank) ?? 0]),
872
+ // HOW MANY ENCODERS IT TAKES. Ranked below every rank of the map and above
873
+ // the swarm's bill, so it cannot buy one where the map is indifferent — and
874
+ // the map IS indifferent about spare capacity, which is what bought an
875
+ // encoder for film nobody waits for.
876
+ encoders: encoders.length,
877
+ // WHAT THE SWARM PAYS for anything fetched twice, which delays everything.
878
+ wasted: wastedSwarm
879
+ };
880
+ }
881
+
882
+ /**
883
+ * Is the first arrangement cheaper than the second?
884
+ *
885
+ * Three things in order, stated by the user 2026-09-06: nobody stares at a
886
+ * spinner; then the film in front of the viewers is finished soonest; then the
887
+ * whole file is. A later one decides only where the earlier ones tie.
888
+ *
889
+ * That order is why an encoder may stand BEHIND a viewer while film in front is
890
+ * still unmade: encoders work at the same time, so one in front and one behind
891
+ * can finish the file sooner than two in front — and where nobody is stalled and
892
+ * the front is closed just as fast, the file being done sooner is the answer.
893
+ *
894
+ * @param {{ stall: number, ahead: number, whole: number }} left
895
+ * @param {{ stall: number, ahead: number, whole: number }} right
896
+ * @returns {boolean}
897
+ */
898
+ function cheaperThan(left, right) {
899
+ // POSITION BY POSITION, in the map's own order of ranks. A difference at a
900
+ // higher rank settles it, and nothing at a lower one can reopen it.
901
+ //
902
+ // There is no margin here and there must not be one. A threshold — "a move
903
+ // must beat staying by at least what moving costs" — was written while the
904
+ // arrival arithmetic charged a run for a piece it had already half made, and
905
+ // it was a prop under a comparison that was wrong rather than indifferent.
906
+ // With the arithmetic right the two are 1.08 s against 1.88 s, and nothing
907
+ // needs propping.
908
+ const size = Math.max(left.byRank.length, right.byRank.length);
909
+ for (let index = 0; index < size; index += 1) {
910
+ const here = left.byRank[index] ?? 0;
911
+ const there = right.byRank[index] ?? 0;
912
+ if (here !== there) {
913
+ return here < there;
914
+ }
915
+ }
916
+ // Where every rank is served identically, fewer encoders. The map is
917
+ // indifferent, so the machine decides: a process, a reader of the piece store
918
+ // and the swarm's bandwidth are all paid by the viewers the ranks above are
919
+ // about.
920
+ if (left.encoders !== right.encoders) {
921
+ return left.encoders < right.encoders;
922
+ }
923
+ return left.wasted < right.wasted;
924
+ }
925
+
926
+ /**
927
+ * How long until a number is needed, read off the map.
928
+ *
929
+ * The map states it per stretch, for the stretch's NEAR EDGE, because a stretch
930
+ * is met at its beginning. Every number inside is needed no sooner than that, so
931
+ * taking the stretch's figure for all of them is the safe reading: it can only
932
+ * make the filling earlier than it has to be, never later.
933
+ *
934
+ * Where the map says nothing, nobody is coming and nothing can be late.
935
+ *
936
+ * Inside a stretch the time GROWS with the distance, because a viewer covers a
937
+ * second of film in a second: the number `n` places past the near edge is
938
+ * reached `n` segments of film later. Taking the near edge's figure for every
939
+ * number inside instead makes a whole stretch due at once — measured while
940
+ * building this: the first stretch is as wide as the measured allowance, so its
941
+ * far end was demanded instantly and an encoder was placed on a number another
942
+ * one was already writing.
943
+ *
944
+ * @param {WantedSpan[]} windows
945
+ * @param {number} segmentSeconds - How much film one number holds.
946
+ * @returns {(index: number) => number}
947
+ */
948
+ /** @param {WantedSpan[]} windows */
949
+ function firstOf(windows) {
950
+ return Math.min(...windows.map((span) => span.from));
951
+ }
952
+
953
+ /** @param {WantedSpan[]} windows */
954
+ function lastOf(windows) {
955
+ return Math.max(...windows.map((span) => span.to));
956
+ }
957
+
958
+ function deadlineReaderFor(windows, segmentSeconds) {
959
+ const perSegment = segmentSeconds > 0 ? segmentSeconds : 0;
960
+ return (index) => {
961
+ let soonest = Number.POSITIVE_INFINITY;
962
+ for (const span of windows) {
963
+ if (index < span.from || index > span.to) {
964
+ continue;
965
+ }
966
+ const stated = /** @type {{ withinSeconds?: number }} */ (span).withinSeconds;
967
+ // A stretch stated with no time is somebody waiting at its near edge: that
968
+ // is what stating one means. The rest of it grows with the distance, the
969
+ // same as a stated one — read as due all at once instead, a window as wide
970
+ // as a viewer's cushion demanded its far end instantly and bought an
971
+ // encoder to stand beside one already working.
972
+ // `null` IS A STATEMENT AND IT SAYS NOBODY IS COMING. `undefined` is the
973
+ // absence of one, and a caller that knows only a position is somebody
974
+ // waiting at it.
975
+ //
976
+ // Read through `Number()`, `null` becomes 0 — due NOW — so the film BEHIND
977
+ // the viewers, which the map marks with exactly that, was the most urgent
978
+ // material in the file. Everything followed from it: it bought encoders,
979
+ // it took the run standing in front of the viewer because that run was the
980
+ // nearest encoder to it, and it did so again on every pass. Field 2026-09-08:
981
+ // 39 moves in one session, 24 between three adjacent numbers, one viewer
982
+ // on three encoders, and the picture stood still for 116.7 s in three
983
+ // interruptions, the worst of them 91.8 s.
984
+ //
985
+ // The map has always said it plainly — `{"from":0,"to":57,"priority":1,
986
+ // "withinSeconds":null,"behind":true}` is in the log of every session — and
987
+ // this line turned it into its opposite. Fourth time in this repository
988
+ // that the input to a calculation was not what the calculation assumed.
989
+ const within = stated === undefined ? 0 : (stated === null ? Number.NaN : Number(stated));
990
+ if (!Number.isFinite(within)) {
991
+ // Stated as no time at all: nobody is coming here.
992
+ continue;
993
+ }
994
+ const here = within + (index - span.from) * perSegment;
995
+ if (here < soonest) {
996
+ soonest = here;
997
+ }
998
+ }
999
+ return soonest;
1000
+ };
1001
+ }
1002
+
1003
+ /**
1004
+ * WHERE ENCODERS BELONG, from the model rather than from a list of cases.
1005
+ *
1006
+ * The problem this solves, stated exactly:
1007
+ *
1008
+ * - the track is a line of segment numbers; `M` are the ones not made;
1009
+ * - each `x` carries a DEADLINE `D(x)`, the seconds until somebody needs it.
1010
+ * That is what the priority map is a reading of — a viewer moving forward
1011
+ * covers a second of film in a second, so the time until they are at `x` is
1012
+ * the distance to it. `Infinity` where nobody is coming;
1013
+ * - an encoder is a SEQUENTIAL producer: placed at `a`, it delivers `a + j` at
1014
+ * time `(j + 1) / r`, where `r` is segments per second, measured. It cannot
1015
+ * skip, so its whole schedule follows from where it starts;
1016
+ * - the machine affords `k` of them, measured.
1017
+ *
1018
+ * Two consequences fall out and need no rule of their own. Placements
1019
+ * `a_1 < ... < a_k` PARTITION the line: encoder `i` is useful only on
1020
+ * `[a_i, a_{i+1})`, because past that its neighbour got there first. And a
1021
+ * segment served by encoder `i` arrives at `(x - a_i + 1) / r`, which is
1022
+ * therefore also the answer to "when would the encoder already placed before it
1023
+ * get here" — the second half of the comparison, and the half that was missing.
1024
+ *
1025
+ * `x` is LATE when it arrives after `D(x)`. The objective is no late segments;
1026
+ * where `k` does not stretch to that, lateness beginning as far to the right as
1027
+ * possible.
1028
+ *
1029
+ * THE ALGORITHM is first-fit, left to right:
1030
+ *
1031
+ * for each missing x with a finite deadline, ascending:
1032
+ * if some encoder already placed at a satisfies (x - a + 1)/r <= D(x):
1033
+ * it covers x
1034
+ * else:
1035
+ * place an encoder at x
1036
+ *
1037
+ * A LIVE run enters as an encoder already placed at its own head. There is no
1038
+ * special case for it.
1039
+ *
1040
+ * WHY IT IS OPTIMAL. The leftmost missing number with a finite deadline must be
1041
+ * covered by somebody. An encoder placed exactly on it delivers it at the
1042
+ * earliest time any placement can, `1/r`, and covers the longest suffix any
1043
+ * placement can — starting further left only re-makes material and arrives
1044
+ * later, starting further right does not cover it at all. So the greedy choice
1045
+ * is never worse than any other, and the usual exchange argument carries it to
1046
+ * the whole line. This is the known result for FIXED-ORDER scheduling with
1047
+ * deadlines, where first-fit is optimal at unit processing times, and a segment
1048
+ * is one unit. General machine minimisation with release times and deadlines is
1049
+ * NP-hard; this case is polynomial because the order is forced and each machine
1050
+ * covers a contiguous stretch.
1051
+ *
1052
+ * WHAT WAS TRIED FIRST AND WAS WRONG, kept because each looked reasonable:
1053
+ *
1054
+ * - `(h - p) * s / (1 - s)`, how long a run stays in front of a viewer moving
1055
+ * forward. It answers a different question: a viewer stopped with an empty
1056
+ * buffer needs the segment now, and at exactly realtime that formula says
1057
+ * "for ever" while the viewer waits thirteen minutes;
1058
+ * - whether a run's head lies inside a wanted band — which ties an encoder to
1059
+ * whoever is standing there, and this layer must never know that;
1060
+ * - the run's head as a barrier, everything above it placeable. It has no time
1061
+ * in it at all, so it cannot tell two segments ahead from two hundred.
1062
+ *
1063
+ * Each was a case, not a model. The deadline is the model.
1064
+ *
1065
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
1066
+ * @param {Set<object>} surviving - Runs that will still be alive, as encoders
1067
+ * already placed at their own heads.
1068
+ * @param {number} rate - Segments produced per second by one encoder, measured.
1069
+ * Zero when nothing has measured it, and then no arrival time can be computed
1070
+ * and every claimed number is left alone.
1071
+ * @returns {(at: number, bound: number, deadlineAt: (index: number) => number, alsoPlaced?: number[]) => number | null}
1072
+ */
1073
+ function gapFinderFor(coverage, surviving, rate, refetchSecPerSegment = 0) {
1074
+ /** Encoders already placed: where each stands, and how far its road runs. */
1075
+ const placed = [];
1076
+ for (const run of surviving) {
1077
+ const head = Number(/** @type {{ head?: number }} */ (run).head);
1078
+ placed.push({
1079
+ at: Number.isFinite(head) ? head : Number(/** @type {{ from: number }} */ (run).from),
1080
+ // A live run's road, so that placing inside it can be priced. A run given
1081
+ // no end drives to the end of the film, which is what makes the price real.
1082
+ // A run given no end drives to the end of the film, which is what makes
1083
+ // the price of cutting in front of it real. Written out rather than
1084
+ // imported: this file depends on nothing, and that is what lets it be
1085
+ // exercised with plain values alone.
1086
+ to: Number(/** @type {{ to: number }} */ (run).to) < Number(/** @type {{ from: number }} */ (run).from)
1087
+ ? Number.POSITIVE_INFINITY
1088
+ : Number(/** @type {{ to: number }} */ (run).to)
1089
+ });
1090
+ }
1091
+ return (at, bound, deadlineAt, alsoPlaced) => {
1092
+ const start = Number.isInteger(at) && at > 0 ? at : 0;
1093
+ const last = Number.isInteger(bound) ? bound : -1;
1094
+ // THE LATE NUMBER THAT IS DUE SOONEST, not the leftmost one.
1095
+ //
1096
+ // With room for every placement the two are the same answer. With a budget
1097
+ // that binds they are not, and the objective decides: lateness pushed as far
1098
+ // to the right as possible means the soonest deadline is served first. A
1099
+ // walk by number gave the one machine to a viewer due in ten minutes while
1100
+ // another stood waiting with an empty buffer.
1101
+ //
1102
+ // Ties go to the smaller number, so the answer does not depend on the order
1103
+ // the map happens to be in.
1104
+ let best = null;
1105
+ let bestDue = Number.POSITIVE_INFINITY;
1106
+ for (let index = start; index <= last; index += 1) {
1107
+ if (coverage.isReady(index)) {
1108
+ continue;
1109
+ }
1110
+ const deadline = deadlineAt(index);
1111
+ if (!Number.isFinite(deadline)) {
1112
+ // NOBODY IS COMING HERE, so nothing can be late — but the film is still
1113
+ // wanted, and this is where spare capacity goes. The number is proposed;
1114
+ // whether an encoder is actually spent on it is the score's answer, and
1115
+ // the score puts anything anybody is waiting for first.
1116
+ return index;
1117
+ }
1118
+ // When would the SOONEST of those already placed get here? Encoders placed
1119
+ // EARLIER IN THIS PASS count: the first one placed for a viewer covers the
1120
+ // stretch in front of them, and without counting it the walk placed a
1121
+ // second and a third on the very next numbers — three processes a segment
1122
+ // apart for one person, which is the waste this model exists to refuse.
1123
+ let soonest = Number.POSITIVE_INFINITY;
1124
+ for (const a of [...placed.map((live) => live.at), ...(alsoPlaced ?? [])]) {
1125
+ if (a > index) {
1126
+ // Standing past it. Encoders only move forward, so it never will.
1127
+ continue;
1128
+ }
1129
+ if (a === index) {
1130
+ // Standing ON it. No placement is faster than the one already made.
1131
+ soonest = 0;
1132
+ break;
1133
+ }
1134
+ // WHEN THIS BODY GETS HERE, and both terms of it.
1135
+ //
1136
+ // Its own encoding of everything between, and the swarm's price for the
1137
+ // film it would fetch a SECOND time — every number between that is
1138
+ // already made, it makes again. That second term is why "should this
1139
+ // encoder drive on or be moved" is not a question of its own: an
1140
+ // encoder with three hundred made pieces in front of it is simply slow
1141
+ // to arrive, and the model compares arrivals. Asked separately it was a
1142
+ // second authority over the same encoder, and the two disagreed.
1143
+ const arrival = (index - a + 1) / rate
1144
+ + coverage.madeBetween(a, index) * refetchSecPerSegment;
1145
+ if (arrival < soonest) {
1146
+ soonest = arrival;
1147
+ }
1148
+ }
1149
+ if (soonest <= deadline) {
1150
+ // Somebody gets here in time. Nothing to decide.
1151
+ continue;
1152
+ }
1153
+ // IT IS LATE, AND THAT IS ALL THIS DECIDES. Whether filling it is worth
1154
+ // the price is not asked here: this only proposes candidates, and the
1155
+ // score decides how many of them are taken and by whom. Asked here as
1156
+ // well, it was a second cost model beside the objective — with its own
1157
+ // idea of what a process costs — and the two disagreed at exactly
1158
+ // realtime, where every next piece is marginally late and each looked
1159
+ // worth its own encoder.
1160
+ if (deadline < bestDue) {
1161
+ best = index;
1162
+ bestDue = deadline;
1163
+ }
1164
+ }
1165
+ return best;
1166
+ };
1167
+ }
1168
+
1169
+ /**
1170
+ * The last number of a stretch that begins at `from` and is `length` long.
1171
+ *
1172
+ * `-1` when the length is not finite, which is this layer's word for a run with
1173
+ * no end: the film's length is not known, so there is nothing to stop it at, and
1174
+ * a number invented here would be an end nobody measured.
1175
+ *
1176
+ * @param {number} from
1177
+ * @param {number} length
1178
+ * @returns {number}
1179
+ */
1180
+ function endOfStretch(from, length) {
1181
+ return Number.isFinite(length) ? from + Math.max(1, length) - 1 : -1;
1182
+ }
1183
+
1184
+ /**
1185
+ * The lowest number a viewer is waiting for that is not ready — what the plan
1186
+ * is judged by.
1187
+ *
1188
+ * Not used to decide anything: it is the figure a log line carries, so that a
1189
+ * plan that keeps producing while a viewer waits is visible rather than
1190
+ * inferred.
1191
+ *
1192
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
1193
+ * @param {WantedSpan[]} windows
1194
+ * @returns {number | null}
1195
+ */
1196
+ export function firstUnmetWant(coverage, windows) {
1197
+ let lowest = null;
1198
+ for (const span of windows ?? []) {
1199
+ for (let at = span.from; at <= span.to; at += 1) {
1200
+ if (!coverage.isReady(at)) {
1201
+ if (lowest === null || at < lowest) {
1202
+ lowest = at;
1203
+ }
1204
+ break;
1205
+ }
1206
+ }
1207
+ }
1208
+ return lowest;
1209
+ }
1210
+
1211
+ /**
1212
+ * Where to put the encoders this machine can afford.
1213
+ *
1214
+ * Two things are wanted of a division of the film, and they are wanted in this
1215
+ * order:
1216
+ *
1217
+ * 1. **the viewer must not stop.** An encoder starting at `q` stays ahead of a
1218
+ * viewer at `p` while `y / s <= q + y - p`, so it holds `(q - p) * s / (1-s)`
1219
+ * of film and no more. Beyond that the viewer catches it, and the next
1220
+ * encoder has to be standing there. That is where the first ones go, and it
1221
+ * is why the stretches grow: the further off one starts, the later the
1222
+ * viewer arrives and the longer it may work;
1223
+ * 2. **the film should be finished as soon as possible.** Once the viewer is
1224
+ * safe, whatever is left is divided EQUALLY between the encoders that
1225
+ * remain: equal shares finish together, and any other division finishes when
1226
+ * its longest share does. That is what makes seeking cheap — the film exists.
1227
+ *
1228
+ * At or above realtime the first requirement is met by one encoder for the
1229
+ * whole film, and every other encoder goes to the second — which is the common
1230
+ * case on a copied picture, and is why "one viewer, one encoder" was never the
1231
+ * rule.
1232
+ *
1233
+ * @param {object} params
1234
+ * @param {import("./CoverageMap.js").CoverageMap} params.coverage
1235
+ * @param {WantedSpan[]} params.windows - The merged map, in this output's own
1236
+ * numbering. Its highest-numbered band starts where the viewer is.
1237
+ * @param {number} params.howMany - What the machine affords.
1238
+ * @param {number} params.speedX - Measured. Zero when nothing has measured it,
1239
+ * and then only the first requirement can be served.
1240
+ * @param {(at: number, bound: number, deadlineAt: (index: number) => number, placed: number[]) => number | null} [params.firstGap] -
1241
+ * Where a gap may be opened. Defaults to the map's own answer; the plan hands
1242
+ * in one that also counts a number a live run has claimed but will not reach
1243
+ * before it is needed, which is the only way anybody beyond a working encoder
1244
+ * is served.
1245
+ * @param {(index: number) => number} [params.deadlineAt] - Seconds until that
1246
+ * number is needed. `Infinity` where nobody is coming. Absent means every
1247
+ * stated want is due now.
1248
+ * @returns {number[]} Where to start each encoder, ascending.
1249
+ */
1250
+ export function placeEncoders({
1251
+ coverage,
1252
+ windows,
1253
+ howMany,
1254
+ firstGap = null,
1255
+ deadlineAt = null,
1256
+ // WHERE TWO ENCODERS SHARE A STRETCH, and whether a second is worth having at
1257
+ // all. Derived by whoever holds the measurements — the rates, the contention
1258
+ // penalty, what a start costs — because this function is positional and holds
1259
+ // none of them. The default is the midpoint, which IS the answer when both are
1260
+ // fresh and owe the same, and is what a caller with nothing measured falls
1261
+ // back on.
1262
+ splitAt = (from, to) => from + Math.floor((to - from + 1) / 2)
1263
+ }) {
1264
+ if (!(howMany > 0) || windows.length === 0) {
1265
+ return [];
1266
+ }
1267
+ // NOW when the caller says nothing. A stated want with no time is somebody
1268
+ // waiting on it — that is what stating one means — so the honest reading is
1269
+ // that it is due. `Infinity` is a statement in its own right and has to be
1270
+ // made: it says nobody is coming.
1271
+ const untilNeeded = deadlineAt ?? (() => 0);
1272
+ /** Where this pass has placed so far — each one covers what it can reach. */
1273
+ const placedHere = [];
1274
+ const gapAt = firstGap
1275
+ ? (at, bound) => firstGap(at, bound, untilNeeded, placedHere)
1276
+ : (at, bound) => coverage.firstGapFrom(at, bound);
1277
+
1278
+
1279
+ // CANDIDATES COME FROM THE PRIORITY MAP, IN THE ORDER THE MAP STATES.
1280
+ //
1281
+ // The map already answers every question that was being re-derived here. Its
1282
+ // ranks say what matters most — the number a viewer is stopped on, then what
1283
+ // is in front of them band by band, then the rest of the track, and last of
1284
+ // all what lies behind them. A pause flattens those ranks; a seek moves them;
1285
+ // a second viewer merges into them. So walking the map in its own order is
1286
+ // what "ahead before behind" means, and nothing here has to work out where the
1287
+ // viewers are.
1288
+ //
1289
+ // It was not read that way. This walked the film by number and proposed
1290
+ // whatever was late, then a second pass divided the leftovers — an order of
1291
+ // its own invention, which put the beginning of the file before the film in
1292
+ // front of a viewer and, at one point, proposed #0, #1 and #2 as three
1293
+ // separate places.
1294
+ //
1295
+ // One candidate per zone: the first number in it nobody has and nobody
1296
+ // reaches in time. Zones with no deadline can have nothing late in them, so
1297
+ // there it is simply the first number nobody has — which is how spare capacity
1298
+ // comes to finish the file.
1299
+ /** @type {number[]} */
1300
+ const places = [];
1301
+ const byRank = [...windows].sort(
1302
+ (left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from
1303
+ );
1304
+ for (const zone of byRank) {
1305
+ if (places.length >= howMany) {
1306
+ break;
1307
+ }
1308
+ const at = gapAt(zone.from, zone.to);
1309
+ if (at === null || places.includes(at)) {
1310
+ continue;
1311
+ }
1312
+ places.push(at);
1313
+ placedHere.push(at);
1314
+ }
1315
+
1316
+ // AND WHERE TO SPLIT WHAT IS LEFT, for the capacity the map has not spent.
1317
+ //
1318
+ // The search above proposes only what is LATE, so once one encoder covers a
1319
+ // zone in time that zone proposes nothing more — and a machine that holds four
1320
+ // ran one. Finishing a contiguous stretch soonest with several machines of the
1321
+ // same speed means dividing it between them, which is where these come from:
1322
+ // the widest run of film between two encoders, split.
1323
+ //
1324
+ // Proposing is not spending. The score decides whether another process is
1325
+ // worth it, and its first term — how late the film is — always outranks its
1326
+ // second, so this can never take capacity from somebody waiting.
1327
+ while (places.length < howMany) {
1328
+ const edges = [...places].sort((left, right) => left - right);
1329
+ let widestFrom = null;
1330
+ let widest = 0;
1331
+ for (let index = 0; index <= edges.length; index += 1) {
1332
+ const from = index === 0 ? firstOf(windows) : edges[index - 1] + 1;
1333
+ const to = index === edges.length ? lastOf(windows) : edges[index] - 1;
1334
+ const room_ = coverage.unmadeRunFrom(from);
1335
+ if (to >= from && room_ > widest) {
1336
+ // WHERE THE TWO OF THEM MEET, calculated rather than halved. Halving is
1337
+ // the answer only when both encoders are fresh and owe the same, and it
1338
+ // was applied to every case — one already working is partway through a
1339
+ // piece while a new one owes its whole start, so the point where they
1340
+ // finish together lies further on. Nothing back means a second encoder
1341
+ // does not pay for itself here at all: two under this host's measured
1342
+ // contention against one at full speed, a comparison halving never made.
1343
+ const meet = splitAt(from, Math.min(from + room_ - 1, to));
1344
+ if (meet !== null) {
1345
+ widest = room_;
1346
+ widestFrom = meet;
1347
+ }
1348
+ }
1349
+ }
1350
+ if (widestFrom === null) {
1351
+ break;
1352
+ }
1353
+ const at = coverage.firstGapFrom(widestFrom, lastOf(windows));
1354
+ if (at === null || places.includes(at)) {
1355
+ break;
1356
+ }
1357
+ places.push(at);
1358
+ placedHere.push(at);
1359
+ }
1360
+
1361
+ // These are CANDIDATES, not decisions. What is late proposes first, because
1362
+ // that is what a viewer feels; what is merely unmade proposes after it. The
1363
+ // score decides which of them are worth a process, and a paused viewer, who
1364
+ // states no deadline at all, therefore still leaves the file being finished
1365
+ // rather than the machine falling idle.
1366
+ return places.sort((left, right) => left - right);
1367
+ }
1368
+