@torrent-tv/proxy 2.85.1 → 2.87.0

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 (381) hide show
  1. package/CHANGELOG.md +2138 -1909
  2. package/CLAUDE.md +318 -197
  3. package/assets/calibration/NOTICE.md +2 -2
  4. package/bin/cli.js +684 -616
  5. package/biome.json +409 -233
  6. package/docs/container-architecture.md +218 -213
  7. package/docs/download-architecture.md +7 -7
  8. package/docs/encode-architecture.md +287 -11
  9. package/docs/encode-run-state.md +2 -2
  10. package/docs/logs.md +97 -97
  11. package/docs/{disk-architecture.md → storage-architecture.md} +107 -1
  12. package/openspec/changes/adaptive-bitrate/design.md +2 -2
  13. package/openspec/changes/adaptive-bitrate/proposal.md +1 -1
  14. package/openspec/changes/adaptive-bitrate/tasks.md +1 -1
  15. package/openspec/changes/chunked-request-bodies/design.md +1 -1
  16. package/openspec/changes/chunked-request-bodies/proposal.md +1 -1
  17. package/openspec/changes/chunked-request-bodies/tasks.md +1 -1
  18. package/openspec/changes/cold-start/design.md +1 -1
  19. package/openspec/changes/disk-cap/proposal.md +1 -1
  20. package/openspec/changes/proxy-observability/proposal.md +2 -2
  21. package/openspec/changes/track-selection/proposal.md +1 -1
  22. package/openspec/changes/transcode-quality/proposal.md +1 -1
  23. package/package.json +2 -2
  24. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  25. package/research/double-spawn-2026-09-10.md +171 -171
  26. package/routes/api/playback-plan/post.js +2 -2
  27. package/routes/api/sources/files/get.js +1 -1
  28. package/routes/api/sources/stats/get.js +1 -1
  29. package/routes/api/sources/warm/post.js +10 -3
  30. package/routes/api/subtitles/get.js +230 -230
  31. package/routes/api/transcode-sessions/fragment-far/post.js +3 -3
  32. package/routes/api/transcode-sessions/net-report/post.js +129 -94
  33. package/routes/api/transcode-sessions/post.js +160 -139
  34. package/routes/api/transcode-sessions/progress/get.js +3 -3
  35. package/routes/api/transcode-sessions/release/post.js +3 -3
  36. package/routes/api/transcode-sessions/seek/post.js +12 -3
  37. package/routes/stream/get.js +2 -2
  38. package/routes/transcode/audio-file/get.js +15 -6
  39. package/routes/transcode/audio-warm/get.js +8 -5
  40. package/routes/transcode/session-file/get.js +429 -268
  41. package/routes/transcode/variant-file/get.js +47 -7
  42. package/routes/transcode/variant-warm/get.js +18 -6
  43. package/scripts/render-run-graph.js +1 -1
  44. package/server.js +720 -465
  45. package/services/encode/CoverageMap.js +428 -428
  46. package/services/encode/CushionReport.js +345 -0
  47. package/services/encode/EncodeAdmission.js +332 -0
  48. package/services/{orchestrators → encode}/EncodeOrchestrator.js +285 -17
  49. package/services/encode/EncodeRun.js +16 -9
  50. package/services/encode/EncodeRuns.js +1219 -0
  51. package/services/encode/Encoder.js +18 -2
  52. package/services/encode/EncoderSelection.js +38 -0
  53. package/services/encode/LocalObservations.js +359 -0
  54. package/services/encode/NvencEncoder.js +5 -0
  55. package/services/encode/OutputOpening.js +745 -0
  56. package/services/encode/OutputTimes.js +579 -0
  57. package/services/encode/Renditions.js +2162 -0
  58. package/services/encode/RunProgress.js +84 -0
  59. package/services/encode/SoftwareEncoder.js +12 -7
  60. package/services/encode/args.js +402 -186
  61. package/services/encode/calibration.js +361 -0
  62. package/services/encode/contention.js +128 -128
  63. package/services/encode/encode-run-state.js +16 -20
  64. package/services/encode/fingerprint.js +322 -0
  65. package/services/{hwaccel.js → encode/hwaccel.js} +82 -42
  66. package/services/{learned-median.js → encode/learned-median.js} +11 -0
  67. package/services/encode/output/EncodedOutput.js +57 -0
  68. package/services/encode/output/Output.js +131 -0
  69. package/services/{output/LiveOutputs.js → encode/output/OutputCatalog.js} +141 -40
  70. package/services/encode/output/OutputSpec.js +390 -0
  71. package/services/{output → encode/output}/Timeline.js +12 -37
  72. package/services/encode/output/index.js +20 -0
  73. package/services/encode/output/ladder.js +32 -0
  74. package/services/{output → encode/output}/playlists.js +3 -0
  75. package/services/encode/output-key-format.js +21 -0
  76. package/services/encode/quality/EncodeCost.js +1083 -0
  77. package/services/encode/quality/HostLoad.js +525 -0
  78. package/services/encode/quality/HostTimings.js +249 -0
  79. package/services/encode/quality/OutputQualityState.js +28 -0
  80. package/services/encode/quality/QualityController.js +931 -0
  81. package/services/encode/quality/QualityOffer.js +416 -0
  82. package/services/encode/quality/drain-threat.js +47 -0
  83. package/services/encode/quality/link-budget.js +254 -0
  84. package/services/encode/quality/output-format.js +266 -0
  85. package/services/encode/quality/serving-output.js +216 -0
  86. package/services/encode/quality/visible-rung.js +57 -0
  87. package/services/encode/run-command.js +23 -20
  88. package/services/encode/run-inputs.js +42 -0
  89. package/services/{segment-formats → encode/segment-formats}/fmp4.js +63 -0
  90. package/services/{segment-formats → encode/segment-formats}/index.js +3 -3
  91. package/services/encode/segment-formats/init-compat.js +324 -0
  92. package/services/{segment-formats → encode/segment-formats}/mp4-boxes.js +8 -3
  93. package/services/encode/throughput.js +97 -0
  94. package/services/{orchestrators → media}/ContainerOrchestrator.js +45 -7
  95. package/services/media/KeyframeTables.js +316 -0
  96. package/services/{source → media}/SourceFile.js +7 -55
  97. package/services/{torrent-worker/subtitle-cues.js → media/SubtitleCues.js} +103 -132
  98. package/services/media/SubtitleOrchestrator.js +167 -0
  99. package/services/{audio-inventory.js → media/audio-inventory.js} +7 -1
  100. package/services/{container → media/container}/AviContainer.js +266 -266
  101. package/services/{container → media/container}/Container.js +596 -601
  102. package/services/media/container/ContainerFactory.js +56 -0
  103. package/services/media/container/KeyframeTable.js +272 -0
  104. package/services/{container → media/container}/MatroskaContainer.js +1485 -1485
  105. package/services/{container → media/container}/Mp4Container.js +1244 -1244
  106. package/services/{container → media/container}/SubtitleFileContainer.js +322 -322
  107. package/services/media/keyframe-probe.js +157 -0
  108. package/services/media/media-info-probe.js +93 -0
  109. package/services/{playback-planner.js → media/playback-planner.js} +82 -39
  110. package/services/{tracks → media/tracks}/AudioTrack.js +131 -131
  111. package/services/{tracks → media/tracks}/language-detect.js +174 -174
  112. package/services/server/OutputLifecycle.js +418 -0
  113. package/services/server/SegmentServing.js +1146 -0
  114. package/services/server/ViewerRequests.js +522 -0
  115. package/services/server/controllers/PlaybackController.js +36 -0
  116. package/services/{controllers → server/controllers}/SubtitleController.js +17 -33
  117. package/services/server/wire-outputs.js +958 -0
  118. package/services/storage/Diagnostics.js +202 -0
  119. package/services/storage/MachineBudget.js +235 -0
  120. package/services/{piece-store → storage}/allowance.js +107 -107
  121. package/services/{core-dumps.js → storage/core-dumps.js} +1 -1
  122. package/services/{files → storage/files}/CompletedFiles.js +116 -1
  123. package/services/{disk → storage}/free.js +33 -0
  124. package/services/storage/machine-memory.js +56 -0
  125. package/services/{memory-report.js → storage/memory-report.js} +575 -596
  126. package/services/{piece-store → storage/piece-store}/piece-disk-store.js +0 -7
  127. package/services/{piece-store → storage/piece-store}/shared-piece-store.js +28 -21
  128. package/services/{encode → storage/segment-store}/SegmentStore.js +395 -8
  129. package/services/storage/wire.js +175 -0
  130. package/services/{download → torrent/download}/SwarmSelection.js +2 -2
  131. package/services/{download → torrent/download}/registry.js +2 -2
  132. package/services/torrent/files.js +1 -1
  133. package/services/torrent/piece-store-of.js +29 -0
  134. package/services/{torrent-pool.js → torrent/torrent-pool.js} +26 -119
  135. package/services/{torrent-worker → torrent/worker}/background-fill.js +2 -2
  136. package/services/{torrent-worker → torrent/worker}/channel.js +271 -250
  137. package/services/{torrent-worker → torrent/worker}/client.js +77 -58
  138. package/services/torrent/worker/held-bytes.js +155 -0
  139. package/services/{torrent-worker → torrent/worker}/install-webrtc-shim.js +1 -1
  140. package/services/{torrent-worker → torrent/worker}/piece-reader.js +21 -30
  141. package/services/{torrent-worker → torrent/worker}/pool-adapter.js +101 -137
  142. package/services/{torrent-worker → torrent/worker}/protocol.js +26 -30
  143. package/services/torrent/worker/resume-warm.js +107 -0
  144. package/services/{torrent-worker → torrent/worker}/webrtc-shim.js +2 -2
  145. package/services/{torrent-worker → torrent/worker}/worker.js +68 -159
  146. package/services/{data-channel-handler.js → transport/data-channel-handler.js} +1356 -1356
  147. package/services/{delivery-probe.js → transport/delivery-probe.js} +842 -842
  148. package/services/{health-collector.js → transport/health-collector.js} +6 -35
  149. package/services/{packet-witness.js → transport/packet-witness.js} +808 -784
  150. package/services/{port-mapper.js → transport/port-mapper.js} +1 -1
  151. package/services/{usrsctp-state.js → transport/usrsctp-state.js} +1 -1
  152. package/services/{webrtc-manager.js → transport/webrtc-manager.js} +1 -1
  153. package/services/viewer/Assignments.js +340 -0
  154. package/services/{priority → viewer}/PriorityMap.js +390 -390
  155. package/services/{priority → viewer}/PriorityOrchestrator.js +325 -320
  156. package/services/viewer/Viewer.js +657 -489
  157. package/services/viewer/Viewers.js +368 -257
  158. package/services/viewer/active-output.js +37 -54
  159. package/services/viewer/audio-start.js +46 -0
  160. package/services/viewer/buffer-trend.js +81 -0
  161. package/services/viewer/choices.js +647 -0
  162. package/services/viewer/positions.js +126 -120
  163. package/services/viewer/report-intake.js +46 -44
  164. package/test/asset-paths.test.js +28 -0
  165. package/test/audio-inventory.test.js +3 -3
  166. package/test/audio-track-bitrate.test.js +40 -0
  167. package/test/auto-quality-step.test.js +707 -518
  168. package/test/available-share.test.js +1 -1
  169. package/test/background-fill.test.js +1 -1
  170. package/test/client-log-file.test.js +110 -110
  171. package/test/completed-files.test.js +1 -1
  172. package/test/concurrent-cost.test.js +13 -3
  173. package/test/container-media-info.test.js +3 -3
  174. package/test/core-dumps.test.js +1 -1
  175. package/test/coverage-follows-the-disk.test.js +40 -8
  176. package/test/cue-push-carries-what-the-walk-found.test.js +58 -0
  177. package/test/cut-times-timeline.test.js +2 -2
  178. package/test/cuts-follow-published-grid.test.js +9 -8
  179. package/test/data-channel-frame.test.js +1 -1
  180. package/test/dead-torrent-handle.test.js +1 -1
  181. package/test/declared-rates.test.js +2 -2
  182. package/test/declared-tracks.test.js +2 -2
  183. package/test/decode-cost-fit.test.js +1 -1
  184. package/test/decode-cost.test.js +34 -25
  185. package/test/delivery-probe.test.js +1 -1
  186. package/test/demand-register.test.js +4 -4
  187. package/test/dht-bootstrap.test.js +1 -1
  188. package/test/drain-threat.test.js +65 -0
  189. package/test/duplicate-add.test.js +1 -1
  190. package/test/encode-admission.test.js +146 -0
  191. package/test/encode-cost.test.js +199 -10
  192. package/test/encode-orchestrator.test.js +39 -1
  193. package/test/encode-plan-viewers.test.js +2 -2
  194. package/test/encode-run.test.js +2 -2
  195. package/test/encode-slope.test.js +1 -1
  196. package/test/encoded-output.test.js +39 -0
  197. package/test/encoder-readings.test.js +1 -1
  198. package/test/every-claimant-is-told-its-share.test.js +152 -0
  199. package/test/failed-encoder-still-serves-what-exists.test.js +354 -0
  200. package/test/failed-start-breaker.test.js +81 -30
  201. package/test/fastest-wires.test.js +1 -1
  202. package/test/ffmpeg-stream-counts.test.js +1 -1
  203. package/test/file-edges.test.js +3 -3
  204. package/test/fmp4-self-contained.test.js +1 -1
  205. package/test/fmp4-timestamps.test.js +1 -1
  206. package/test/fmp4-track-completeness.test.js +1 -1
  207. package/test/format-keyed-outputs.test.js +78 -0
  208. package/test/health-metrics.test.js +3 -2
  209. package/test/held-request-width.test.js +22 -23
  210. package/test/helpers/encode-run.js +136 -136
  211. package/test/helpers/held-file.js +29 -0
  212. package/test/helpers/manager.js +57 -0
  213. package/test/helpers/output-spec.js +63 -0
  214. package/test/host-load.test.js +1 -1
  215. package/test/index-accuracy-is-about-the-file.test.js +128 -0
  216. package/test/init-compat.test.js +219 -0
  217. package/test/input-lost-quiets-the-plan.test.js +1 -1
  218. package/test/input-unavailable.test.js +1 -1
  219. package/test/keeping-period.test.js +4 -4
  220. package/test/keyframe-index-accuracy.test.js +97 -45
  221. package/test/keyframe-table-budget.test.js +28 -33
  222. package/test/keyframes-belong-to-the-file.test.js +174 -57
  223. package/test/learned-median.test.js +1 -1
  224. package/test/letting-go-asks-who-is-watching.test.js +191 -0
  225. package/test/limit-row-by-area.test.js +60 -0
  226. package/test/link-budget.test.js +111 -0
  227. package/test/link-probe.test.js +56 -56
  228. package/test/local-encoding-data.test.js +273 -0
  229. package/test/look-ahead-coverage.test.js +1 -1
  230. package/test/manager-surface.test.js +294 -0
  231. package/test/matroska-blocks.test.js +0 -0
  232. package/test/matroska-cues-track.test.js +1 -1
  233. package/test/memory-budget.test.js +2 -2
  234. package/test/mp4-composition-times.test.js +0 -0
  235. package/test/mp4-subtitles.test.js +1 -1
  236. package/test/one-authority.test.js +45 -41
  237. package/test/one-budget.test.js +149 -0
  238. package/test/one-output-one-session.test.js +204 -0
  239. package/test/{disk-space.test.js → one-resource-divided.test.js} +30 -10
  240. package/test/one-serving-output-per-height.test.js +458 -0
  241. package/test/orchestrator-wired.test.js +46 -45
  242. package/test/output-catalog.test.js +39 -0
  243. package/test/output-shape.test.js +4 -51
  244. package/test/output-spec.test.js +251 -157
  245. package/test/output-speed.test.js +17 -15
  246. package/test/outputs-being-prepared.test.js +40 -0
  247. package/test/packet-witness-ring.test.js +2 -2
  248. package/test/packet-witness.test.js +1 -1
  249. package/test/piece-disk-store.test.js +2 -2
  250. package/test/piece-from-whole-file.test.js +1 -1
  251. package/test/piece-lru.test.js +1 -1
  252. package/test/piece-reader.test.js +2 -2
  253. package/test/piece-store-eviction.test.js +1 -1
  254. package/test/piece-store-never-refuses.test.js +1 -1
  255. package/test/piece-store-reservations.test.js +1 -1
  256. package/test/piece-store-slow-disk.test.js +1 -1
  257. package/test/piece-tail.test.js +1 -1
  258. package/test/plan-host-timings.test.js +1 -1
  259. package/test/plan-is-steady.test.js +225 -225
  260. package/test/priority-map-download.test.js +4 -4
  261. package/test/priority-map-emptied.test.js +204 -205
  262. package/test/priority-map-per-output.test.js +215 -209
  263. package/test/priority-map.test.js +1 -1
  264. package/test/probe-wedge-certainty.test.js +1 -1
  265. package/test/produced-copy-choice.test.js +15 -60
  266. package/test/quality-offer.test.js +162 -0
  267. package/test/quality-variants.test.js +1229 -1167
  268. package/test/rate-control-in-the-output.test.js +180 -0
  269. package/test/read-survives-withdrawal.test.js +2 -2
  270. package/test/read-window.test.js +10 -3
  271. package/test/resume-warm.test.js +1 -1
  272. package/test/run-inputs.test.js +80 -0
  273. package/test/run-position-follows-published-grid.test.js +13 -11
  274. package/test/run-progress.test.js +65 -0
  275. package/test/same-height-switch.test.js +664 -0
  276. package/test/seek-frees-the-viewers-requests.test.js +217 -0
  277. package/test/seek-landing.test.js +13 -13
  278. package/test/seek-target-not-superseded.test.js +28 -29
  279. package/test/segment-closed-on-both-branches.test.js +96 -0
  280. package/test/segment-cut-times.test.js +1 -1
  281. package/test/segment-hold-supersede.test.js +28 -35
  282. package/test/segment-judged-by-its-own-header.test.js +221 -0
  283. package/test/segment-serve-wiring.test.js +130 -39
  284. package/test/segment-store-eviction.test.js +22 -7
  285. package/test/segment-store.test.js +98 -14
  286. package/test/segment-true-start.test.js +1 -1
  287. package/test/segments-are-shared.test.js +17 -16
  288. package/test/send-chunk-bytes.test.js +1 -1
  289. package/test/serving-existing-output.test.js +102 -0
  290. package/test/serving-output.test.js +102 -0
  291. package/test/shared-piece-store.test.js +1 -1
  292. package/test/source-file.test.js +1 -1
  293. package/test/stale-request-after-seek.test.js +17 -21
  294. package/test/startup-readings.test.js +10 -5
  295. package/test/subtitle-cue-framing.test.js +5 -5
  296. package/test/subtitle-cue-source.test.js +36 -38
  297. package/test/subtitle-cue-walk.test.js +11 -10
  298. package/test/subtitle-defaults.test.js +1 -1
  299. package/test/subtitle-language.test.js +4 -4
  300. package/test/subtitle-track-numbering.test.js +5 -4
  301. package/test/supply-margin.test.js +1 -1
  302. package/test/swarm-follows-readers.test.js +3 -3
  303. package/test/swarm-reach.test.js +1 -1
  304. package/test/swarm-selection.test.js +3 -3
  305. package/test/tail-duplication.test.js +1 -1
  306. package/test/the-channel-has-both-ends.test.js +91 -0
  307. package/test/the-torrent-thread-serves-bytes.test.js +107 -0
  308. package/test/thread-pool.test.js +3 -3
  309. package/test/timeline.test.js +1 -12
  310. package/test/torrent-cost.test.js +1 -1
  311. package/test/tracks-begin-together.test.js +38 -24
  312. package/test/tunnel-renewal.test.js +1 -1
  313. package/test/two-viewers-one-picture.test.js +120 -87
  314. package/test/upload-hurry.test.js +3 -3
  315. package/test/usrsctp-state.test.js +1 -1
  316. package/test/video-facts.test.js +1 -1
  317. package/test/viewer-assignments.test.js +143 -0
  318. package/test/viewer-outputs.test.js +60 -52
  319. package/test/viewer-presence.test.js +22 -25
  320. package/test/viewer-requests-admission.test.js +89 -0
  321. package/test/viewer-states.test.js +189 -172
  322. package/test/viewer-subtitle-subscription.test.js +1 -1
  323. package/test/viewer.test.js +139 -136
  324. package/test/viewing-generations.test.js +390 -0
  325. package/test/visible-rung.test.js +37 -0
  326. package/test/wait-ledger.test.js +1 -1
  327. package/test/webrtc-shim.test.js +3 -3
  328. package/test/wedge-certainty.test.js +2 -2
  329. package/test/withdraw-piece-claim.test.js +2 -2
  330. package/test/worker-channel.test.js +1 -31
  331. package/utils/client-log-file.js +151 -151
  332. package/scripts/read-container-index.mjs +0 -108
  333. package/services/container/ContainerFactory.js +0 -122
  334. package/services/controllers/PlaybackController.js +0 -33
  335. package/services/disk/DiskSpace.js +0 -150
  336. package/services/disk/wire.js +0 -61
  337. package/services/hls-session-manager.js +0 -9689
  338. package/services/orchestrators/SubtitleOrchestrator.js +0 -160
  339. package/services/output/Output.js +0 -94
  340. package/services/output/OutputSpec.js +0 -202
  341. package/services/output/index.js +0 -1
  342. package/services/output/ladder.js +0 -26
  343. package/services/produced-index.js +0 -222
  344. package/services/quality/EncodeCost.js +0 -555
  345. package/services/torrent-worker/container-tracks.js +0 -414
  346. package/test/produced-index.test.js +0 -142
  347. /package/{services → bin}/thread-pool.js +0 -0
  348. /package/services/{available-share.js → encode/available-share.js} +0 -0
  349. /package/services/{decode-cost-fit.js → encode/decode-cost-fit.js} +0 -0
  350. /package/services/{encoder-readings.js → encode/encoder-readings.js} +0 -0
  351. /package/services/{host-load.js → encode/host-load.js} +0 -0
  352. /package/services/{output → encode/output}/cut-grid.js +0 -0
  353. /package/services/{output → encode/output}/rates.js +0 -0
  354. /package/services/{segment-formats → encode/segment-formats}/mpegts.js +0 -0
  355. /package/services/{torrent-cost.js → encode/torrent-cost.js} +0 -0
  356. /package/services/{container → media/container}/ebml-reader.js +0 -0
  357. /package/services/{ffmpeg-banner.js → media/ffmpeg-banner.js} +0 -0
  358. /package/services/{tracks → media/tracks}/ContainerTrack.js +0 -0
  359. /package/services/{tracks → media/tracks}/ImageSubtitleTrack.js +0 -0
  360. /package/services/{tracks → media/tracks}/SubtitleTrack.js +0 -0
  361. /package/services/{tracks → media/tracks}/TextSubtitleTrack.js +0 -0
  362. /package/services/{tracks → media/tracks}/VideoTrack.js +0 -0
  363. /package/services/{tracks → media/tracks}/index.js +0 -0
  364. /package/services/{files → storage/files}/piece-from-whole-file.js +0 -0
  365. /package/services/{disk → storage}/keep.js +0 -0
  366. /package/services/{piece-store → storage/piece-store}/piece-lru.js +0 -0
  367. /package/services/{disk → storage}/returns.js +0 -0
  368. /package/services/{demand → torrent/demand}/DemandRegister.js +0 -0
  369. /package/services/{demand → torrent/demand}/Urgency.js +0 -0
  370. /package/services/{demand → torrent/demand}/Window.js +0 -0
  371. /package/services/{demand → torrent/demand}/index.js +0 -0
  372. /package/services/{demand → torrent/demand}/pieces.js +0 -0
  373. /package/services/{download → torrent/download}/withdraw-claim.js +0 -0
  374. /package/services/{supply-margin.js → torrent/supply-margin.js} +0 -0
  375. /package/services/{torrent-source-key.js → torrent/torrent-source-key.js} +0 -0
  376. /package/services/{torrent-worker → torrent/worker}/fastest-wires.js +0 -0
  377. /package/services/{torrent-worker → torrent/worker}/handle-state.js +0 -0
  378. /package/services/{nat-classifier.js → transport/nat-classifier.js} +0 -0
  379. /package/services/{registry-api.js → transport/registry-api.js} +0 -0
  380. /package/services/{tunnel-client.js → transport/tunnel-client.js} +0 -0
  381. /package/services/{priority → viewer}/WaitLedger.js +0 -0
@@ -6,127 +6,244 @@
6
6
  * used to read it twice — which is what two viewers opening one film do,
7
7
  * measured 13 ms apart on 2026-09-03 — and the answer decides whether the
8
8
  * picture can be copied at all, so it has to be one answer.
9
+ *
10
+ * And it has to be one OBJECT, not one value: a session created while the read
11
+ * is still running must see the answer when it lands. Held as a value it could
12
+ * not, and the read that outran its budget was lost to every session already
13
+ * made.
9
14
  */
10
15
 
11
16
  import test from "node:test";
12
17
  import assert from "node:assert/strict";
13
- import { HlsSessionManager } from "../services/hls-session-manager.js";
14
- import { Container } from "../services/container/Container.js";
18
+ import { KeyframeTables } from "../services/media/KeyframeTables.js";
19
+ import { KeyframeTable } from "../services/media/container/KeyframeTable.js";
20
+ import { Container } from "../services/media/container/Container.js";
21
+
22
+ const QUIET = { info: () => {}, warn: () => {} };
15
23
 
16
24
  /**
17
- * @returns {HlsSessionManager}
25
+ * @param {(params: object) => Promise<object | null>} readTable
26
+ * @param {number} [budgetMs]
27
+ * @returns {KeyframeTables}
18
28
  */
19
- function manager() {
20
- return new HlsSessionManager({
21
- enabled: true,
22
- ffmpegBin: "ffmpeg",
23
- localBindHost: "127.0.0.1",
24
- localPort: 9090
25
- });
29
+ function tables(readTable, budgetMs = 1_000) {
30
+ return new KeyframeTables({ readTable, budgetMs, logger: QUIET });
26
31
  }
27
32
 
28
- test("two sessions asking at once make one read and join one wait", async () => {
29
- const session = manager();
33
+ const FILE = { sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" };
34
+
35
+ test("two askers at once make one read and join one wait", async () => {
30
36
  let reads = 0;
31
37
  let answer = null;
32
- session.getContainerKeyframes = () => {
38
+ const keyframes = tables(() => {
33
39
  reads += 1;
34
40
  return new Promise((resolve) => {
35
41
  answer = resolve;
36
42
  });
37
- };
43
+ });
38
44
 
39
- const first = session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
40
- const second = session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
45
+ const first = keyframes.warm(FILE);
46
+ const second = keyframes.warm(FILE);
41
47
  assert.equal(reads, 1, "the second asker joined the read already running");
42
48
 
43
- answer({ times: [0, 4, 8], tolerance: 0 });
49
+ answer({ times: [0, 4, 8], tolerance: 0, format: "matroska" });
44
50
  await Promise.all([first, second]);
45
51
  assert.equal(reads, 1);
46
52
  });
47
53
 
48
- test("the answer is remembered for the file, so a later session reads nothing", async () => {
49
- const session = manager();
54
+ test("the answer is remembered for the file, so a later asker reads nothing", async () => {
50
55
  let reads = 0;
51
- session.getContainerKeyframes = async () => {
56
+ const keyframes = tables(async () => {
52
57
  reads += 1;
53
- return { times: [0, 4, 8], tolerance: 0 };
54
- };
58
+ return { times: [0, 4, 8], tolerance: 0, format: "matroska" };
59
+ });
55
60
 
56
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
57
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
61
+ await keyframes.warm(FILE);
62
+ await keyframes.warm(FILE);
58
63
 
59
64
  assert.equal(reads, 1);
60
65
  });
61
66
 
62
67
  test("two files of one torrent are two answers", async () => {
63
- const session = manager();
64
68
  const asked = [];
65
- session.getContainerKeyframes = async ({ fileIndex }) => {
69
+ const keyframes = tables(async ({ fileIndex }) => {
66
70
  asked.push(fileIndex);
67
- return { times: [0, 4], tolerance: 0 };
68
- };
71
+ return { times: [0, 4], tolerance: 0, format: "matroska" };
72
+ });
69
73
 
70
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
71
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 1, logName: "b.mkv" });
74
+ await keyframes.warm({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.mkv" });
75
+ await keyframes.warm({ sourceKey: "torrent:abc", fileIndex: 1, logName: "b.mkv" });
72
76
 
73
77
  assert.deepEqual(asked, [0, 1]);
74
78
  });
75
79
 
76
80
  test("a file with no readable index says so once, and keeps saying it", async () => {
77
- const session = manager();
78
81
  let reads = 0;
79
- session.getContainerKeyframes = async () => {
82
+ const keyframes = tables(async () => {
80
83
  reads += 1;
81
84
  return null;
82
- };
85
+ });
83
86
 
84
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.ts" });
85
- await session.warmKeyframeIndex({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.ts" });
87
+ await keyframes.warm({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.ts" });
88
+ await keyframes.warm({ sourceKey: "torrent:abc", fileIndex: 0, logName: "a.ts" });
86
89
 
87
90
  // "No index" is an answer about the file — it is what makes a copy of it
88
91
  // re-encode instead — and it must be the same answer for every viewer.
89
92
  assert.equal(reads, 1);
93
+ const table = keyframes.of(FILE);
94
+ assert.equal(table.answered, true, "something came back");
95
+ assert.equal(table.readable, false, "and what came back was nothing");
96
+ });
97
+
98
+ test("a table read after a session was made still reaches it", async () => {
99
+ let answer = null;
100
+ const keyframes = tables(() => new Promise((resolve) => { answer = resolve; }), 30);
101
+
102
+ // What a session does: ask for the file's table, wait as long as it may, and
103
+ // carry whatever it was handed.
104
+ const { table, arrived } = await keyframes.within(FILE);
105
+ assert.equal(arrived, false, "the read outran the budget");
106
+ assert.equal(table.answered, false, "and nothing has answered yet, which is not the same as no keyframes");
107
+
108
+ answer({ times: [0, 4, 8], tolerance: 0, format: "matroska" });
109
+ await new Promise((resolve) => { setImmediate(resolve); });
110
+
111
+ // The session is holding THIS object, so the late answer is in its hands
112
+ // without anybody having gone round telling it.
113
+ assert.equal(table.answered, true);
114
+ assert.deepEqual(table.times, [0, 4, 8]);
115
+ assert.equal(keyframes.of(FILE), table, "and the file still has one table, not two");
90
116
  });
91
117
 
92
- test("a container reads its own table once", async () => {
118
+ test("a read that threw is not an answer, and the next asker reads again", async () => {
119
+ let reads = 0;
120
+ const keyframes = tables(async () => {
121
+ reads += 1;
122
+ if (reads === 1) {
123
+ // The bytes it needed had not arrived. That says nothing about the file,
124
+ // and recording it as "no keyframes" would re-encode every picture of
125
+ // this file for as long as the process lives.
126
+ throw new Error("the head is not downloaded");
127
+ }
128
+ return { times: [0, 6], tolerance: 0, format: "matroska" };
129
+ });
130
+
131
+ await assert.rejects(() => keyframes.read(FILE), /the head is not downloaded/);
132
+ assert.equal(keyframes.of(FILE).answered, false);
133
+
134
+ const table = await keyframes.read(FILE);
135
+
136
+ assert.equal(reads, 2, "it was read again rather than refused from a cached failure");
137
+ assert.deepEqual(table.times, [0, 6]);
138
+ });
139
+
140
+ test("the packet probe never displaces a fuller table", () => {
141
+ const keyframes = tables(async () => ({ times: [0, 2, 4, 6, 8], tolerance: 0, format: "matroska" }));
142
+ keyframes.learn(FILE, { times: [0, 2, 4, 6, 8], format: "matroska" });
143
+
144
+ // Measured 2026-08-02: a packet scan found 77 keyframes in 45 s without
145
+ // finishing, against all 570 in 0.8 s from the container's own index.
146
+ keyframes.learn(FILE, { times: [0, 8], format: "packet probe" });
147
+
148
+ const table = keyframes.of(FILE);
149
+ assert.deepEqual(table.times, [0, 2, 4, 6, 8]);
150
+ assert.equal(table.format, "matroska");
151
+ });
152
+
153
+ test("the packet probe IS the answer where no container index exists", () => {
154
+ const keyframes = tables(async () => null);
155
+ keyframes.learn(FILE, { times: null, format: "mpegts" });
156
+ assert.equal(keyframes.of(FILE).readable, false);
157
+
158
+ keyframes.learn(FILE, { times: [0, 3, 6], format: "packet probe" });
159
+
160
+ assert.deepEqual(keyframes.of(FILE).times, [0, 3, 6]);
161
+ });
162
+
163
+ test("a registry with no reader says nothing about the file rather than lying about it", async () => {
164
+ const keyframes = new KeyframeTables({ logger: QUIET });
165
+
166
+ const table = await keyframes.read(FILE);
167
+
168
+ assert.equal(table.readable, false, "there is no table, so a picture of this file is re-encoded");
169
+ assert.equal(
170
+ table.answered,
171
+ false,
172
+ "and nothing has ANSWERED — a proxy wired without a reader is not a statement about anybody's bytes"
173
+ );
174
+ });
175
+
176
+ test("a table nobody holds is dropped, and one still being read is not", async () => {
177
+ let answer = null;
178
+ const keyframes = tables(() => new Promise((resolve) => { answer = resolve; }));
179
+ const held = keyframes.of({ sourceKey: "torrent:abc", fileIndex: 0 });
180
+ const dropped = keyframes.of({ sourceKey: "torrent:abc", fileIndex: 1 });
181
+ void keyframes.warm({ sourceKey: "torrent:abc", fileIndex: 2, logName: "c.mkv" });
182
+ const reading = keyframes.of({ sourceKey: "torrent:abc", fileIndex: 2 });
183
+
184
+ keyframes.forgetUnused(new Set([held]));
185
+
186
+ assert.equal(keyframes.of({ sourceKey: "torrent:abc", fileIndex: 0 }), held);
187
+ assert.notEqual(keyframes.of({ sourceKey: "torrent:abc", fileIndex: 1 }), dropped);
188
+ assert.equal(
189
+ keyframes.of({ sourceKey: "torrent:abc", fileIndex: 2 }),
190
+ reading,
191
+ "dropping a file whose read is in flight loses the answer and pays the whole wait again"
192
+ );
193
+ answer(null);
194
+ });
195
+
196
+ test("the container reads and does not remember — one fact, one store", async () => {
197
+ // It used to keep the answer, which made this table the one fact in the proxy
198
+ // stored twice: here, and in the file's own `KeyframeTable`. Traced
199
+ // 2026-09-15, this copy had no reader: nothing in the torrent thread asks
200
+ // where a file's keyframes are, and the one path to it ends at
201
+ // `KeyframeTables` on the other side of the channel.
93
202
  let parses = 0;
94
- class OneTable extends Container {
203
+ class Counting extends Container {
95
204
  async parseKeyframeIndex() {
96
205
  parses += 1;
97
206
  return { times: [0, 2, 4], tolerance: 0 };
98
207
  }
99
208
  }
100
- const container = new OneTable({ readRange: async () => null, fileSize: 10 });
209
+ const container = new Counting({ readRange: async () => null, fileSize: 10 });
101
210
 
102
- const [first, second] = await Promise.all([
103
- container.readKeyframeIndex(),
104
- container.readKeyframeIndex()
105
- ]);
211
+ await container.readKeyframeIndex();
106
212
  await container.readKeyframeIndex();
107
213
 
108
- assert.equal(parses, 1);
109
- assert.deepEqual(first, second);
214
+ assert.equal(parses, 2, "a container that keeps the answer is a second owner of it");
110
215
  });
111
216
 
112
- test("a read that threw is not remembered as an answer", async () => {
217
+ test("reading once per file is the table registry's job, and it also bounds the wait", async () => {
218
+ // Where the guarantee went. It is not merely moved: this is the only place
219
+ // that can ALSO stop a viewer waiting for ever while letting the read finish,
220
+ // which a container cannot — it does not know there is a viewer.
113
221
  let parses = 0;
114
- class Late extends Container {
222
+ class Counting extends Container {
115
223
  async parseKeyframeIndex() {
116
224
  parses += 1;
117
- if (parses === 1) {
118
- // The bytes it needed had not arrived yet, which is not a statement
119
- // about the file.
120
- throw new Error("nothing to read there yet");
121
- }
122
- return { times: [0, 2], tolerance: 0 };
225
+ return { times: [0, 2, 4], tolerance: 0 };
123
226
  }
124
227
  }
125
- const container = new Late({ readRange: async () => null, fileSize: 10 });
228
+ const container = new Counting({ readRange: async () => null, fileSize: 10 });
229
+ const keyframes = tables(() => container.readKeyframeIndex());
230
+
231
+ await Promise.all([keyframes.read(FILE), keyframes.read(FILE)]);
232
+ await keyframes.read(FILE);
233
+
234
+ assert.equal(parses, 1);
235
+ assert.deepEqual(keyframes.of(FILE).times, [0, 2, 4]);
236
+ });
237
+
238
+ test("answered and readable are two questions, and a bag of fields cannot tell them apart", () => {
239
+ const table = new KeyframeTable();
240
+ assert.equal(table.answered, false);
241
+ assert.equal(table.readable, false);
242
+ assert.equal(table.format, "not yet read");
126
243
 
127
- await assert.rejects(() => container.readKeyframeIndex());
128
- const second = await container.readKeyframeIndex();
244
+ table.learn({ times: null, format: "mpegts" });
129
245
 
130
- assert.equal(parses, 2);
131
- assert.deepEqual(second.times, [0, 2]);
246
+ assert.equal(table.answered, true, "the container came back");
247
+ assert.equal(table.readable, false, "with no keyframes, which is permanent for this file");
248
+ assert.equal(table.format, "mpegts", "and the refusal can name what it is refusing");
132
249
  });
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import assert from "node:assert/strict";
6
6
  import { test } from "node:test";
7
- import { medianOf, movedBeyondScatter, scatterOf } from "../services/learned-median.js";
7
+ import { medianOf, movedBeyondScatter, scatterOf } from "../services/encode/learned-median.js";
8
8
 
9
9
  test("the median is the middle reading, and the mean of the two middle ones", () => {
10
10
  assert.equal(medianOf([3, 1, 2]), 2);
@@ -0,0 +1,191 @@
1
+ /**
2
+ * @file Letting go of a step must ask who is on it, at the moment of letting go.
3
+ *
4
+ * Two disposals in the step path reasoned "nobody is on it yet", and neither
5
+ * could know it. An output is addressed by what it PRODUCES, so opening one
6
+ * hands back the output that already makes that picture whenever there is one —
7
+ * which may be a step another viewer has been watching all along. And a
8
+ * genuinely new one is only nobody's until something else reaches it: making a
9
+ * step takes a probe and a keyframe index, seconds in which a second viewer can
10
+ * ask for the same height and be registered onto it.
11
+ *
12
+ * Both are the same fault, so both are one question asked of the registry now.
13
+ */
14
+
15
+ import test from "node:test";
16
+ import assert from "node:assert/strict";
17
+ import { Renditions } from "../services/encode/Renditions.js";
18
+ import { Viewers } from "../services/viewer/Viewers.js";
19
+ import {
20
+ chooseOutput,
21
+ chosenOutputOf,
22
+ noteServingVerdict,
23
+ audioBeingWarmedOf,
24
+ audioChoiceOf,
25
+ chooseAudioTrack,
26
+ consumersOn,
27
+ linkMbpsOf,
28
+ noteAudioBeingWarmed,
29
+ noteStepBeingWarmed,
30
+ noteStepOnScreen,
31
+ placeOn,
32
+ presentOn,
33
+ qualityModeOf,
34
+ stepBeingWarmedOf,
35
+ stepOnScreenOf,
36
+ watches
37
+ } from "../services/viewer/choices.js";
38
+ import { SourceFile } from "../services/media/SourceFile.js";
39
+
40
+ const BASE_ID = "4444444455556666";
41
+ const STEP_ID = "5555555566667777";
42
+
43
+ /**
44
+ * A picture with one step of 720p, and whatever `createOrGetSession` is told to
45
+ * hand back for the next request.
46
+ *
47
+ * @param {{ handBack: (() => object) | null, baseIsLive?: boolean, stepProducedHeight?: number }} how
48
+ */
49
+ function renditionsOver(how) {
50
+ const file = new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" });
51
+ // THE SAME MATERIAL, stated in full, because that is what the rule compares:
52
+ // the source, the container, the cut grid, what the output carries and which
53
+ // tracks. Two outputs of one picture differ in SIZE and in nothing else, and
54
+ // a stub that leaves those fields out is not a picture with two rungs — it is
55
+ // two outputs the rule cannot recognise as related.
56
+ const material = () => ({
57
+ transcodesAudio: false,
58
+ sourceKey: "source-1",
59
+ segmentFormatId: "fmp4",
60
+ grid: { toKey: () => "kf@0:100" },
61
+ carries: "video-only",
62
+ video: { fileIndex: 0 },
63
+ audio: null
64
+ });
65
+ const base = { id: BASE_ID, outputKey: "letting-go:base", file, spec: material(), timeline: { cutGrid: "uniform" }, segmentFormat: { id: "fmp4" } };
66
+ const step = { id: STEP_ID, outputKey: "letting-go:step", file, spec: material(), timeline: { cutGrid: "uniform" }, segmentFormat: { id: "fmp4" } };
67
+ const viewers = new Viewers();
68
+ const disposed = [];
69
+ const lines = [];
70
+ const outputs = {
71
+ get: (id) => (id === BASE_ID ? base : id === STEP_ID ? step : null),
72
+ touch: () => {},
73
+ markStep: () => {},
74
+ stepsOf: () => [step],
75
+ splicableHeights: () => [1080, 720],
76
+ // The step is NAMED 540 and may PRODUCE something else: an output answers
77
+ // for the picture it makes, not for the number in its name.
78
+ variantHeightOf: (output) => (output === base ? 1080 : 540),
79
+ // What each actually makes. The picture itself is a rung like any other,
80
+ // and when it is a re-encode a step can land on exactly its size — which is
81
+ // the case the adoption below exists for.
82
+ producedHeightOf: (output) => (output === base ? (how.baseProducedHeight ?? 1080) : (how.stepProducedHeight ?? 540)),
83
+ values: () => [base, step]
84
+ };
85
+ const renditions = new Renditions({
86
+ outputs,
87
+ viewerCountOn: (output) => viewers.forOutput(output).size,
88
+ outputStillNeeded: (output) => viewers.stillNeeded(output),
89
+ consumersOn: (output) => consumersOn(viewers, output),
90
+ presentOn: (output) => presentOn(viewers, output),
91
+ qualityModeOf: (output, consumerId) => qualityModeOf(viewers, output, consumerId),
92
+ linkMbpsOf: (output, consumerId) => linkMbpsOf(viewers, output, consumerId),
93
+ audioChoiceOf: (output, consumerId) => audioChoiceOf(viewers, output, consumerId),
94
+ chooseAudioTrack: (output, consumerId, trackIndex) => chooseAudioTrack(viewers, output, consumerId, trackIndex),
95
+ stepOnScreenOf: (output, consumerId) => stepOnScreenOf(viewers, output, consumerId),
96
+ noteStepOnScreen: (output, consumerId, stepId) => noteStepOnScreen(viewers, output, consumerId, stepId),
97
+ stepBeingWarmedOf: (output, consumerId) => stepBeingWarmedOf(viewers, output, consumerId),
98
+ noteStepBeingWarmed: (output, consumerId, stepId) => noteStepBeingWarmed(viewers, output, consumerId, stepId),
99
+ audioBeingWarmedOf: (output, consumerId) => audioBeingWarmedOf(viewers, output, consumerId),
100
+ noteAudioBeingWarmed: (output, consumerId, id) => noteAudioBeingWarmed(viewers, output, consumerId, id),
101
+ watches: (output, consumerId) => watches(viewers, output, consumerId),
102
+ placeOn: (output, consumerId, seconds) => placeOn(viewers, output, consumerId, seconds),
103
+ // Which output answers a height for a viewer is the viewer's own record.
104
+ chosenOutputOf: (consumerId, height) => chosenOutputOf(viewers, consumerId, height),
105
+ chooseOutput: (consumerId, height, key) => chooseOutput(viewers, consumerId, height, key),
106
+ noteServingVerdict: (consumerId, verdict) => noteServingVerdict(viewers, consumerId, verdict),
107
+ placeViewerOn: () => {},
108
+ viewerSecondsOn: () => 0,
109
+ activeOutputFor: () => base,
110
+ viewerPositionOf: () => 0,
111
+ outputTimes: { segmentStartTime: () => 0 },
112
+ encodeRuns: { isLive: () => how.baseIsLive !== false },
113
+ quality: { variantsOnScreen: () => new Set() },
114
+ createOrGetSession: async () => how.handBack(),
115
+ disposeSession: async (id) => { disposed.push(id); },
116
+ planEncodersSoon: () => {},
117
+ viewerLeaves: () => {},
118
+ logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line), error: (line) => lines.push(line) }
119
+ });
120
+ return { renditions, base, step, viewers, disposed, lines };
121
+ }
122
+
123
+ test("an output handed back because it already makes this picture is not taken from its viewers", async () => {
124
+ // What `createOrGetSession` returns for a 720p request: the step that is
125
+ // already producing it, which somebody has been watching all along.
126
+ // The picture is itself re-encoded at 720 on this machine, so the step asked
127
+ // for produces the same picture it does: the case adoption is written for,
128
+ // and the one where what is let go of may be somebody's.
129
+ const { renditions, step, viewers, disposed } = renditionsOver({
130
+ handBack: () => step,
131
+ baseProducedHeight: 720,
132
+ stepProducedHeight: 720
133
+ });
134
+ viewers.of(step, "viewer-b");
135
+
136
+ const resolved = await renditions.resolveVariantSession(BASE_ID, 720, -1, "viewer-a");
137
+
138
+ assert.equal(resolved?.id, BASE_ID, "the incumbent making this picture answers for the height");
139
+ assert.deepEqual(disposed, [], "and the step handed back is not taken from the viewer on it");
140
+ });
141
+
142
+ test("a step a second viewer reached while it was being made is not disposed under them", async () => {
143
+ // The picture dies while the step is being prepared — the case the disposal
144
+ // was written for — but a second viewer has reached the step meanwhile.
145
+ const made = { id: STEP_ID };
146
+ const { renditions, viewers, disposed, lines } = renditionsOver({
147
+ baseIsLive: false,
148
+ handBack: () => {
149
+ // Registered onto it inside the window the disposal assumes is empty.
150
+ viewers.of(made, "viewer-b");
151
+ return made;
152
+ }
153
+ });
154
+
155
+ const resolved = await renditions.resolveVariantSession(BASE_ID, 720, -1, "viewer-a");
156
+
157
+ assert.equal(resolved, null, "the viewer who asked has lost the picture it was a step of");
158
+ assert.deepEqual(disposed, [], "but the step itself is somebody's now");
159
+ assert.ok(lines.some((line) => line.includes("kept although")), "and the reason is in the log");
160
+ });
161
+
162
+ test("a step nobody reached is still let go of when its picture dies", async () => {
163
+ const made = { id: STEP_ID };
164
+ const { renditions, disposed } = renditionsOver({ baseIsLive: false, handBack: () => made });
165
+
166
+ const resolved = await renditions.resolveVariantSession(BASE_ID, 720, -1, "viewer-a");
167
+
168
+ assert.equal(resolved, null);
169
+ assert.deepEqual(disposed, [STEP_ID], "nothing holds it, and it would hold an encoder until its idle timer");
170
+ });
171
+
172
+ test("a step nobody is watching is kept while a response from it is still being sent", async () => {
173
+ // The case the assignment exists for: the last viewer has stopped being
174
+ // registered on the output, and its bytes are still going out. Asked at the
175
+ // moment of letting go, which is the only moment at which the answer is
176
+ // about now.
177
+ const made = { id: STEP_ID, outputKey: "letting-go:made" };
178
+ const { renditions, viewers, disposed, lines } = renditionsOver({ baseIsLive: false, handBack: () => made });
179
+ const elsewhere = viewers.of({ id: "some-other-output" }, "viewer-c");
180
+ const token = elsewhere.assignments.accept(made.outputKey);
181
+
182
+ const resolved = await renditions.resolveVariantSession(BASE_ID, 720, -1, "viewer-a");
183
+
184
+ assert.equal(resolved, null, "the viewer who asked has lost the picture it was a step of");
185
+ assert.deepEqual(disposed, [], "but the output a response is being sent from is not taken away");
186
+ assert.ok(lines.some((line) => line.includes("kept although")), "and the reason is in the log");
187
+
188
+ // And once the response is done, nothing stands on it any more.
189
+ elsewhere.assignments.release(token);
190
+ assert.equal(viewers.stillNeeded(made), false);
191
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @file The row of bitrate limits is chosen by the AREA of the frame, not by
3
+ * its height (roadmap item 97, step 14; decided with the user 2026-09-24).
4
+ *
5
+ * The rows are the frames of the ladder at 16:9, as the encode itself sizes
6
+ * them. A frame takes the row nearest by the ratio of areas; on the exact
7
+ * border the larger row wins; a row with no nominal of its own takes the
8
+ * nominal of the nearest row that has one.
9
+ */
10
+
11
+ import test from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { h264LevelFor, limitRowFor, nominalKbpsFor, softwareRateControlFor } from "../services/encode/args.js";
14
+
15
+ test("a 2.4:1 film in a 1080 box is priced as 1080, not as 720", () => {
16
+ // 1920x800 is 1.54 million points: 1.35 times below the 1080 row, 1.67
17
+ // times above the 720 row. A height alone put it in the 720 row.
18
+ assert.equal(limitRowFor({ width: 1920, height: 800 }), 1080);
19
+ assert.equal(nominalKbpsFor({ width: 1920, height: 800 }), nominalKbpsFor({ width: 1920, height: 1080 }));
20
+ });
21
+
22
+ test("the 16:9 frames of the ladder each land in their own row", () => {
23
+ for (const [width, height] of [[3840, 2160], [2560, 1440], [1920, 1080], [1280, 720], [960, 540], [852, 480], [640, 360], [426, 240]]) {
24
+ assert.equal(limitRowFor({ width, height }), height, `${width}x${height}`);
25
+ }
26
+ });
27
+
28
+ test("a wide 720 frame falls in the 540 row and takes the nominal the 540 row borrows", () => {
29
+ // 1280x534 is 0.68 million points: 1.32 times above the 540 row and 1.35
30
+ // times below the 720 row. The 540 row has no nominal of its own yet, and the
31
+ // nearest row by area that has one is 480.
32
+ assert.equal(limitRowFor({ width: 1280, height: 534 }), 540);
33
+ assert.equal(nominalKbpsFor({ width: 1280, height: 534 }), nominalKbpsFor({ width: 852, height: 480 }));
34
+ });
35
+
36
+ test("on the exact border between two rows the larger row wins", () => {
37
+ // The border between 1280x720 (921600) and 1920x1080 (2073600) is their
38
+ // geometric mean, 1382400 = 1440x960, 1.5 times from each.
39
+ assert.equal(limitRowFor({ width: 1440, height: 960 }), 1080);
40
+ });
41
+
42
+ test("rows with no nominal of their own borrow the nearest row that has one", () => {
43
+ assert.equal(nominalKbpsFor({ width: 2560, height: 1440 }), nominalKbpsFor({ width: 1920, height: 1080 }));
44
+ assert.equal(nominalKbpsFor({ width: 3840, height: 2160 }), nominalKbpsFor({ width: 1920, height: 1080 }));
45
+ assert.equal(nominalKbpsFor({ width: 960, height: 540 }), nominalKbpsFor({ width: 852, height: 480 }));
46
+ });
47
+
48
+ test("the level of a wide frame is declared from the nominal of its row", () => {
49
+ const control = softwareRateControlFor({ width: 1920, height: 800, fps: 24 });
50
+ const nominal = nominalKbpsFor({ width: 1920, height: 1080 });
51
+ assert.equal(
52
+ control.level,
53
+ h264LevelFor({ width: 1920, height: 800, fps: 24, maxrateKbps: control.maxrateKbps, bufsizeKbps: control.bufsizeKbps })
54
+ );
55
+ assert.equal(control.maxrateKbps, Math.round(nominal * 1.3));
56
+ });
57
+
58
+ test("a frame with no area is refused rather than priced", () => {
59
+ assert.throws(() => limitRowFor({ width: 0, height: 720 }), RangeError);
60
+ });