@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
@@ -0,0 +1,931 @@
1
+ /**
2
+ * @file The quality budget of the outputs that exist: when a picture is asked to
3
+ * move to another height, when its bitrate is capped by a viewer's measured link,
4
+ * and what the player is told to follow.
5
+ *
6
+ * Moved out of the session manager whole (plan step 3). What it needs of the
7
+ * rest of the proxy is the host object it is built with, and nothing else.
8
+ */
9
+
10
+ import { stat } from "node:fs/promises";
11
+ import { logger } from "../../../utils/logger.js";
12
+ import { ENCODE_RUN_STATE } from "../encode-run-state.js";
13
+ import { LINK_SAFETY, linkCouldCarry, loadOf } from "./link-budget.js";
14
+ import { qualityStateOf } from "./OutputQualityState.js";
15
+ import { drainThreat } from "./drain-threat.js";
16
+ import { visibleHeightCap } from "./visible-rung.js";
17
+
18
+ // Realtime budget — runtime downswitch (software encoder only). Periodically
19
+ // check each active software-transcode session's ffmpeg `speed`; when it stays
20
+ // below realtime for a sustained window AND the input is not download-starved
21
+ // (so the limit is the encoder, not the torrent), step down one resolution rung
22
+ // and restart at the current segment. Conservative so it never thrashes: a long
23
+ // sustained window, a post-action cooldown, a step cap, and no upswitch (v1).
24
+ export const BUDGET_CHECK_INTERVAL_MS = 5_000;
25
+ // Speed below this (cumulative ffmpeg average) counts as "slow"; recovery to
26
+ // realtime resets the slow window (hysteresis).
27
+ const BUDGET_SPEED_SLOW = 0.95;
28
+ const BUDGET_SPEED_OK = 1.0;
29
+ // Slow must persist this long before a downshift (absorbs warm-up + brief
30
+ // complex scenes; the cumulative average won't dip this long unless the host
31
+ // genuinely can't keep up).
32
+ const BUDGET_SUSTAINED_MS = 15_000;
33
+ // The step BACK UP has to be slower to fire than the step down, or the two
34
+ // take turns: a rung that has just been left is by definition one the arithmetic
35
+ // still thinks this machine can hold, so it would be asked for again as soon as
36
+ // the cooldown expired. Four times the down window is a statement about how long
37
+ // a machine has to look able before it is believed, not a measured quantity, and
38
+ // it is written here rather than dressed up as one.
39
+ const BUDGET_UP_SUSTAINED_MS = 60_000;
40
+ // How long a request to the player to change variant stands before it is
41
+ // treated as unanswered. A progress report is polled about every 1.5 s and the
42
+ // switch itself needs the rung warmed, which is the cold start this host
43
+ // measures; this is long enough for both and short enough that a browser which
44
+ // cannot honour the request (no master playlist, a viewer on a manual pick) is
45
+ // not chased for the rest of the film.
46
+ const QUALITY_ASK_TTL_MS = 45_000;
47
+ // The input counts as "keeping up" when the torrent downloads at least this
48
+ // multiple of the source's average byte rate. Below it (and not yet fully
49
+ // downloaded), a low speed is download-bound, not CPU-bound → do NOT downscale.
50
+ const BUDGET_DOWNLOAD_OK_FACTOR = 1.0;
51
+ // Viewer-link adaptation. Judged on each report a viewer makes, for that
52
+ // viewer alone (roadmap item 98): when their link does not carry the stream
53
+ // they are given AND their buffer, on its present trend, would run dry before
54
+ // another output could have the piece they need (`drain-threat.js`), a smaller
55
+ // output is prepared for them. A chosen window of slowness and a chosen buffer
56
+ // threshold stood here, and a chosen wait after every action; all three are
57
+ // gone. A manual viewer is never sent an automatic quality request.
58
+ // Observed produced bitrate: average over this many recently completed
59
+ // segments (the newest file on disk may still be written and is excluded).
60
+ const LINK_OBSERVED_SEGMENTS = 5;
61
+
62
+ export class QualityController {
63
+ /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
64
+ #host;
65
+
66
+ /** A budget pass is under way; a timer tick that lands meanwhile is skipped. */
67
+ #tickRunning = false;
68
+
69
+ /** Viewers whose report is being judged now (`noteViewerReported`). @type {Set<string>} */
70
+ #judging = new Set();
71
+
72
+ /**
73
+ * @param {object} host - `isLive`, `liveConsumers`, `liveRunsOf`, `producedNumbers`, `reportHostLoad`, `runStateOf`, `sampleDownloadRates`, `encodeCost`, `getSourceStats`, `outputs`, `qualityOffer`, `segmentDurationSec`, `segmentStore`, `videoEncoder`, `prepareSameHeightSwitch`, `sameHeightSwitchPending`, `sameHeightSwitchDirection`, `cancelSameHeightSwitch`, `heightReadyFor`, `bufferOf`, `visiblePictureOf`, `expectedFirstSegmentMs`
74
+ */
75
+ constructor(host) {
76
+ this.#host = host;
77
+ }
78
+
79
+ /**
80
+ * One pass of the quality budget: learn what this host is doing with each
81
+ * running encode, and act on it.
82
+ *
83
+ * Public because it is an operation with a name, not an implementation
84
+ * detail of a timer — and because a loop that decides what the viewer sees
85
+ * and can only be reached through `setInterval` is a loop nothing can check.
86
+ * The timer calls exactly this.
87
+ *
88
+ * @returns {Promise<void>}
89
+ */
90
+ async runQualityBudgetOnce() {
91
+ void this.#host.reportHostLoad();
92
+ // One tick at a time. Both halves await torrent statistics per source, so a
93
+ // slow or stuck answer would otherwise let the next tick in behind it — two
94
+ // passes over the same sessions, taking the same reading twice and acting
95
+ // on the same speed twice, and an earlier tick's rates landing on top of a
96
+ // later tick's.
97
+ if (this.#tickRunning === true) {
98
+ return;
99
+ }
100
+ this.#tickRunning = true;
101
+ try {
102
+ // Taken whatever the encoder is: the torrent's price is charged against
103
+ // this rate on every host, not only on the ones that re-encode.
104
+ await this.#host.sampleDownloadRates();
105
+ if (this.#host.videoEncoder?.kind !== "software") {
106
+ return;
107
+ }
108
+ await this.#realtimeBudgetPass();
109
+ } finally {
110
+ this.#tickRunning = false;
111
+ }
112
+ }
113
+
114
+ async #realtimeBudgetPass() {
115
+ const now = Date.now();
116
+ for (const session of this.#host.outputs.values()) {
117
+ // What this file costs to decode is learned from EVERY encoding session,
118
+ // before any of the budget's own conditions are consulted. Those exist to
119
+ // decide whether to step the quality, and they exclude most of what is
120
+ // worth measuring: a rung already at the foot of its ladder has nowhere
121
+ // to step, and a 240p variant IS its whole ladder — which is exactly the
122
+ // rung the field measured at 0.95x on 2026-08-15, learning nothing from
123
+ // three minutes of it because the loop had already skipped the session as
124
+ // un-actionable.
125
+ await this.#host.encodeCost.learnFrom(session);
126
+ if (
127
+ !session ||
128
+ !this.#host.isLive(session) ||
129
+ this.#host.runStateOf(session) === ENCODE_RUN_STATE.ENDED_FAILED ||
130
+ // Nothing is encoding, so there is no speed to judge. A variant the
131
+ // viewer has switched away from is left in exactly this state, and its
132
+ // last recorded speed would otherwise buy it a step — which restarts
133
+ // the encoder it was just stopped for.
134
+ this.#host.liveRunsOf(session).length === 0 ||
135
+ // A soundtrack published on its own carries no picture, so no quality
136
+ // step is its to make; its price is learned above and that is all.
137
+ session.spec.carries === "audio-only"
138
+ ) {
139
+ continue;
140
+ }
141
+ // A viewer's link is judged on each of their reports
142
+ // (`noteViewerReported`), not here: nothing about it changes between two
143
+ // reports, so a timer would only read the same statement again.
144
+ if (await this.#checkEncoderBudget(session, now)) {
145
+ continue;
146
+ }
147
+ await this.#checkStepUp(session, now);
148
+ }
149
+ }
150
+
151
+ /**
152
+ * The encoder-speed check for one session: sustained sub-realtime, and the
153
+ * encoder — not a download-starved input — is the limit.
154
+ *
155
+ * @param {HlsSession} session
156
+ * @param {number} now
157
+ * @returns {Promise<boolean>} True when a step was asked for this tick.
158
+ */
159
+ async #checkEncoderBudget(session, now) {
160
+ if (!session.spec.transcodesVideo) {
161
+ // A copy has no encoder to make cheaper. Whatever the machine is short
162
+ // of, moving this viewer to a RE-ENCODED rung costs it more, not less —
163
+ // so the copy path's only lever is the viewer's link, above.
164
+ return false;
165
+ }
166
+ const speed = this.#host.encodeCost.recentSpeedOf(session, now, BUDGET_CHECK_INTERVAL_MS * 2);
167
+ if (speed === null) {
168
+ return false; // no measurement yet
169
+ }
170
+ if (speed >= BUDGET_SPEED_OK) {
171
+ qualityStateOf(session).budgetSlowSince = 0; // recovered — reset the slow window
172
+ return false;
173
+ }
174
+ if (speed >= BUDGET_SPEED_SLOW) {
175
+ return false; // in the hysteresis band; neither slow nor ok
176
+ }
177
+ if (qualityStateOf(session).budgetSlowSince === 0) {
178
+ qualityStateOf(session).budgetSlowSince = now;
179
+ return false;
180
+ }
181
+ if (now - qualityStateOf(session).budgetSlowSince < BUDGET_SUSTAINED_MS) {
182
+ return false; // not sustained yet
183
+ }
184
+ const bound = await this.classifyTranscodeBound(session);
185
+ if (bound === "download") {
186
+ logger.info(
187
+ `[budget] transcode ${session.id} speed=${speed.toFixed(2)}x but download-limited ` +
188
+ `"${session.file.name}"; not stepping down (torrent is the bottleneck)`
189
+ );
190
+ qualityStateOf(session).budgetSlowSince = 0; // re-evaluate fresh; don't thrash on this
191
+ return false;
192
+ }
193
+ qualityStateOf(session).budgetSlowSince = 0;
194
+ qualityStateOf(session).budgetUpSince = 0;
195
+ const boundLabel = bound === "unknown" ? "assuming CPU-bound" : "CPU-bound";
196
+ // The machine is the output's reason, so every viewer with it on screen is
197
+ // asked — each to the rung their own picture bounds a re-encode by, where
198
+ // that is lower than the next rung down (roadmap item 98).
199
+ const reasonText = `${boundLabel} speed=${speed.toFixed(2)}x`;
200
+ const base = this.#host.outputs.pictureOf(session);
201
+ const watching = this.#host.presentOn(session).filter((consumerId) => this.#onScreenHere(session, consumerId));
202
+ if (watching.length === 0) {
203
+ return this.#askLowerHeight(session, reasonText);
204
+ }
205
+ let asked = false;
206
+ for (const consumerId of watching) {
207
+ if (this.#askLowerHeight(session, reasonText, [consumerId], { cap: this.#visibleCapOf(base, consumerId) })) {
208
+ asked = true;
209
+ }
210
+ }
211
+ return asked;
212
+ }
213
+
214
+ /**
215
+ * Ask the player to move down one offered rung.
216
+ *
217
+ * THE SIZE OF THE PICTURE IS NEVER REWRITTEN UNDERNEATH A RUNNING SESSION.
218
+ * The fMP4 init segment is fetched once — a player reads `#EXT-X-MAP` and
219
+ * never asks again — and `avc1` keeps SPS and PPS in it rather than in the
220
+ * fragments, so every fragment produced after a size change is decoded
221
+ * against parameter sets describing a picture that is no longer being made.
222
+ * Measured 2026-08-21 on two files: one browser went on reporting
223
+ * `size=1280x720` for three and a half minutes over a band of macroblock
224
+ * garbage after the encoder had left for 960x540; the other errored on the
225
+ * first mismatched fragment, closed the MediaSource and sat at `size=0x0`
226
+ * for four and a half minutes. Which of the two happens is the decoder's
227
+ * choice, not ours, and no layer reported an error either time.
228
+ *
229
+ * A change of resolution is a change of VARIANT, as the standard has it.
230
+ * Every height is already published in the master with its own init, so the
231
+ * step is made by ASKING the browser to move — the same act the manual menu
232
+ * performs, which has never had this fault.
233
+ *
234
+ * @param {HlsSession} session
235
+ * @param {string} reasonText
236
+ * @param {string[] | null} [onlyFor]
237
+ * @param {{ urgent?: boolean, cap?: number | null }} [options] - `urgent`
238
+ * when the viewer's buffer would run dry first; `cap` the height the
239
+ * picture they see bounds a re-encode by, preferred where it is lower than
240
+ * the next rung down.
241
+ * @returns {boolean} True when an ask was recorded.
242
+ */
243
+ #askLowerHeight(session, reasonText, onlyFor = null, { urgent = false, cap = null } = {}) {
244
+ const base = this.#host.outputs.pictureOf(session);
245
+ const current = this.#host.outputs.variantHeightOf(session);
246
+ const offered = this.#host.qualityOffer.offeredHeights(base);
247
+ // The highest rung strictly below the one on screen that this host is still
248
+ // willing to serve. `offeredHeights` has already refused everything the
249
+ // machine cannot hold, so a rung that survives it is one worth moving to.
250
+ // Where the picture the viewer sees bounds a re-encode lower still, the
251
+ // highest rung within that bound is taken instead: they are shown nothing
252
+ // the rung between would have added (roadmap item 98).
253
+ const lower = this.#host.outputs.splicableHeights(base)
254
+ .filter((height) => height < current && offered.includes(height));
255
+ const next = (Number.isInteger(cap) && cap > 0 ? lower.find((height) => height <= cap) : undefined) ?? lower[0];
256
+ if (next === undefined) {
257
+ // Nothing lower — but "lower" is not the same question as "cheaper", and
258
+ // on a source that is COPIED the answer is above, not below. A copied
259
+ // rung costs no encoder at all, whatever its size, so when a re-encode
260
+ // cannot keep up it is both the fastest thing this host can serve AND the
261
+ // best picture it has.
262
+ //
263
+ // Field 2026-08-31, and it cost the viewer the whole film: an ultrafast
264
+ // 444x240 encode ran at 0.43-0.94x for fifty minutes while the source's
265
+ // own 1038p sat on offer beside it, copied and free. This line printed
266
+ // fifty times — "nothing lower is on offer; leaving the picture alone" —
267
+ // and the picture stood still 161 times for 940 seconds. The rescue was
268
+ // on the screen the whole time and the rule could only look down.
269
+ const copied = this.#host.qualityOffer.copiedHeightOf(base);
270
+ if (copied > 0 && copied !== current && offered.includes(copied)) {
271
+ logger.info(
272
+ `[budget] transcode ${session.id} ${reasonText} at ${current}p and nothing lower is on offer, ` +
273
+ `but ${copied}p is COPIED on this file — no encoder at all, and a better picture. ` +
274
+ `Asking for it instead of leaving the viewer on an encode that cannot keep up`
275
+ );
276
+ return this.#askQualityHeight(base, copied, reasonText, onlyFor, urgent);
277
+ }
278
+ logger.info(
279
+ `[budget] transcode ${session.id} ${reasonText} at ${current}p, but nothing lower is on offer ` +
280
+ `for "${session.file.name}"; leaving the picture alone`
281
+ );
282
+ return false;
283
+ }
284
+ return this.#askQualityHeight(base, next, reasonText, onlyFor, urgent);
285
+ }
286
+
287
+ /**
288
+ * Record a request to the viewer's player to move to another variant.
289
+ *
290
+ * The proxy cannot move a player between variants; it can only say which one
291
+ * it would rather serve. The request travels in every progress report, and
292
+ * the browser honours it ONLY in automatic mode — a height the viewer picked
293
+ * by hand is theirs, and nothing here may take it away.
294
+ *
295
+ * @param {HlsSession} base
296
+ * @param {number} height
297
+ * @param {string} reasonText
298
+ * @param {string[] | null} [onlyFor] - The viewers this ask is FOR. A reason
299
+ * that belongs to one person's link is theirs alone: a thin link asks only
300
+ * the viewer on it, never everybody watching the picture. Null for a reason
301
+ * that belongs to the output — the machine cannot keep up with it — which
302
+ * is every AUTO viewer's.
303
+ * @param {boolean} [urgent] - Their buffer would run dry before anything else
304
+ * could arrive, so their page switches without waiting for a cushion.
305
+ * @returns {boolean}
306
+ */
307
+ #askQualityHeight(base, height, reasonText, onlyFor = null, urgent = false) {
308
+ if (!this.#host.outputs.publishesVariants(base)) {
309
+ // Said once for the session. Repeating it is not information: the answer
310
+ // is a property of the stream and cannot change while it plays.
311
+ if (qualityStateOf(base).saidNoVariants !== true) {
312
+ qualityStateOf(base).saidNoVariants = true;
313
+ logger.info(
314
+ `[budget] transcode ${base.id} would ask for ${height}p, but this stream publishes no ` +
315
+ `variants to move between; leaving the picture alone for the rest of the session`
316
+ );
317
+ }
318
+ return false;
319
+ }
320
+ const now = Date.now();
321
+ const asked = [];
322
+ const playing = [];
323
+ for (const consumerId of this.#host.consumersOn(base)) {
324
+ if (this.#host.qualityModeOf(base, consumerId) !== "auto") {
325
+ continue;
326
+ }
327
+ if (onlyFor && !onlyFor.includes(consumerId)) {
328
+ continue;
329
+ }
330
+ const onScreen = this.#host.stepOnScreenOf(base, consumerId);
331
+ const current = onScreen ? this.#host.outputs.get(onScreen) : base;
332
+ const currentHeight = this.#host.outputs.variantHeightOf(current ?? base);
333
+ playing.push(currentHeight);
334
+ if (currentHeight === height) {
335
+ this.#host.dropAskOf(base, consumerId);
336
+ continue;
337
+ }
338
+ const standing = this.#host.standingAskOf(base, consumerId);
339
+ if (standing && standing.height === height && now - standing.at < QUALITY_ASK_TTL_MS) {
340
+ continue;
341
+ }
342
+ if (this.#host.askQualityOf(base, consumerId, height, reasonText, now, urgent)) {
343
+ asked.push(consumerId);
344
+ }
345
+ }
346
+ if (asked.length === 0) {
347
+ return false;
348
+ }
349
+ logger.info(
350
+ `[budget] transcode ${base.id} asks the player to move ${playing.join("p/")}p → ${height}p${urgent ? " (urgent)" : ""}: ${reasonText} ` +
351
+ `"${base.file.name}" for ${asked.length} AUTO viewer(s) ` +
352
+ `(a change of size is a change of variant — its own init describes it)`
353
+ );
354
+ return true;
355
+ }
356
+
357
+ /**
358
+ * The step BACK UP, in two stages and one rung at a time.
359
+ *
360
+ * 1. ANOTHER LIMIT OF THE SAME HEIGHT: a viewer moved down to a lower limit
361
+ * goes back up the limits of their height first, without their player
362
+ * being told (roadmap item 97, step 12). A limit is part of an output, so
363
+ * this is a move between outputs, prepared for one viewer.
364
+ * 2. ANOTHER HEIGHT, asked of the player in AUTO — only for a viewer with no
365
+ * higher limit to go to on the height they watch, and only if their own
366
+ * link admits the next height's whole load.
367
+ *
368
+ * Both follow one window: the machine and the viewer's link have held the
369
+ * output on screen, with room to spare, for four times as long as a step
370
+ * DOWN needs.
371
+ *
372
+ * @param {HlsSession} session
373
+ * @param {number} now
374
+ * @returns {Promise<void>}
375
+ */
376
+ async #checkStepUp(session, now) {
377
+ const base = this.#host.outputs.pictureOf(session);
378
+ const current = this.#host.outputs.variantHeightOf(session);
379
+ // What the machine and the link would have to look like for a step up, held
380
+ // for a window four times the one a step DOWN needs. Anything that fails
381
+ // resets it, so the window measures an unbroken stretch.
382
+ const spare = this.#roomToSpare(session, now);
383
+ // A step up being prepared for a viewer who no longer has room is let go:
384
+ // the conditions it was asked under have gone back (roadmap item 98).
385
+ for (const consumerId of this.#host.presentOn(session)) {
386
+ if (!spare.includes(consumerId)) {
387
+ this.#dropUpAsk(session, consumerId, "the room it was asked for has gone");
388
+ }
389
+ }
390
+ if (spare.length === 0) {
391
+ qualityStateOf(session).budgetUpSince = 0;
392
+ return;
393
+ }
394
+ if (qualityStateOf(session).budgetUpSince === 0) {
395
+ qualityStateOf(session).budgetUpSince = now;
396
+ return;
397
+ }
398
+ if (now - qualityStateOf(session).budgetUpSince < BUDGET_UP_SUSTAINED_MS) {
399
+ return;
400
+ }
401
+ qualityStateOf(session).budgetUpSince = 0;
402
+ const reasonText =
403
+ `the machine and the link have carried ${current}p for ` +
404
+ `${Math.round(BUDGET_UP_SUSTAINED_MS / 1000)}s with room to spare`;
405
+ const atTheirHighestLimit = [];
406
+ for (const consumerId of spare) {
407
+ const move = await this.#host.prepareSameHeightSwitch(session, consumerId, "up", reasonText);
408
+ if (move.started) {
409
+ continue;
410
+ }
411
+ // Refused because the MACHINE holds no more encoders: a higher height
412
+ // costs more than the limit that was just refused, so it is not asked for.
413
+ if (move.noPlace) {
414
+ logger.info(`[budget] transcode ${session.id} no step up for ${consumerId}: ${move.reason}`);
415
+ continue;
416
+ }
417
+ atTheirHighestLimit.push(consumerId);
418
+ }
419
+ // One rung at a time: the lowest height above the one on screen, never
420
+ // above the source (upscaling invents detail and costs more than the
421
+ // source itself). A second step follows a second unbroken window.
422
+ const higher = this.#host.qualityOffer.nextHeightUp(base, current);
423
+ if (higher === undefined) {
424
+ return;
425
+ }
426
+ // Only the viewers whose OWN link admits the next rung, and whose picture on
427
+ // screen is not already served by the rung they are on: a re-encode is
428
+ // never made taller than the picture they see (roadmap item 98). The copy
429
+ // of the source is not a re-encode, and going back to it is not bounded.
430
+ // Another viewer's fast link or large screen says nothing about theirs.
431
+ const copied = this.#host.qualityOffer.copiedHeightOf(base);
432
+ const carriers = atTheirHighestLimit.filter((consumerId) =>
433
+ this.#linkAdmitsHeight(base, session, consumerId, higher) &&
434
+ (higher === copied || this.#visibleCapOf(base, consumerId) === null || higher <= this.#visibleCapOf(base, consumerId))
435
+ );
436
+ if (carriers.length > 0) {
437
+ this.#askQualityHeight(base, higher, reasonText, carriers);
438
+ }
439
+ }
440
+
441
+ /**
442
+ * The viewers who have this session on screen with room to spare: the
443
+ * encoder ahead of realtime and the torrent not the limit — which are the
444
+ * OUTPUT's and hold for all of them or none — and, for each viewer on their
445
+ * own, a buffer that is not draining and no move of theirs already being
446
+ * prepared.
447
+ *
448
+ * @param {HlsSession} session
449
+ * @param {number} now
450
+ * @returns {string[]} Empty when nobody has room.
451
+ */
452
+ #roomToSpare(session, now) {
453
+ if (session.spec.transcodesVideo) {
454
+ const speed = this.#host.encodeCost.recentSpeedOf(session, now, BUDGET_CHECK_INTERVAL_MS * 2);
455
+ if (speed === null || speed < BUDGET_SPEED_OK) {
456
+ return [];
457
+ }
458
+ }
459
+ if (qualityStateOf(session).budgetSlowSince !== 0) {
460
+ return [];
461
+ }
462
+ // A buffer that drains over a whole segment's period is being spent faster
463
+ // than it is filled: there is no room for more.
464
+ return this.#host.presentOn(session).filter((consumerId) =>
465
+ !((this.#host.bufferOf(session, consumerId, this.#host.segmentDurationSec)?.slope ?? 0) < 0) &&
466
+ this.#onScreenHere(session, consumerId) &&
467
+ !this.#host.sameHeightSwitchPending(consumerId)
468
+ );
469
+ }
470
+
471
+ /**
472
+ * Whether this viewer's own link admits the whole load of a height nothing
473
+ * may have produced yet.
474
+ *
475
+ * Nothing measured their link: no ground to refuse, the same silence that
476
+ * stops `#checkViewerLink` from acting on them.
477
+ *
478
+ * @param {HlsSession} base
479
+ * @param {HlsSession} session
480
+ * @param {string} consumerId
481
+ * @param {number} height
482
+ * @returns {boolean}
483
+ */
484
+ #linkAdmitsHeight(base, session, consumerId, height) {
485
+ const report = this.#host.linkReportOf(session, consumerId);
486
+ const load = loadOf(
487
+ this.#host.qualityOffer.videoLoadFor(base, height, this.#host.videoEncoder?.kind ?? ""),
488
+ this.#host.viewerAudioLoadOf(base, consumerId)
489
+ );
490
+ return linkCouldCarry(report?.linkMbps ?? null, load).admitted;
491
+ }
492
+
493
+ /**
494
+ * A viewer reported on themselves: judge their link and the picture they
495
+ * see, for them alone, now (roadmap item 98).
496
+ *
497
+ * The report is the event that carries a change of either, so it is where
498
+ * they are judged — not a timer, which between two reports would only read
499
+ * the same statement again.
500
+ *
501
+ * @param {string} sessionId - The output the page addressed.
502
+ * @param {string} consumerId
503
+ * @returns {Promise<void>}
504
+ */
505
+ async noteViewerReported(sessionId, consumerId) {
506
+ const named = sessionId ? this.#host.outputs.get(sessionId) : null;
507
+ if (!named || !consumerId) {
508
+ return;
509
+ }
510
+ const base = this.#host.outputs.pictureOf(named);
511
+ const onScreen = this.#host.stepOnScreenOf(base, consumerId);
512
+ const session = (onScreen ? this.#host.outputs.get(onScreen) : null) ?? base;
513
+ if (!this.#host.isLive(session) || session.spec.carries === "audio-only") {
514
+ return;
515
+ }
516
+ // One judgement of a viewer at a time: reports can arrive while the last
517
+ // one is still reading its files.
518
+ if (this.#judging.has(consumerId)) {
519
+ return;
520
+ }
521
+ this.#judging.add(consumerId);
522
+ try {
523
+ const now = Date.now();
524
+ if (this.#host.videoEncoder?.kind === "software" &&
525
+ (await this.#checkViewerLink(session, consumerId, now))) {
526
+ return;
527
+ }
528
+ this.#checkVisiblePicture(session, consumerId, now);
529
+ } finally {
530
+ this.#judging.delete(consumerId);
531
+ }
532
+ }
533
+
534
+ /**
535
+ * This viewer's link against the stream they are given.
536
+ *
537
+ * THE CONDITION, both halves measured: their link does not carry the stream
538
+ * (the reading times the safety margin is below the observed bitrate), and
539
+ * their buffer, on its present trend, would run dry before another output
540
+ * could close the piece they need (`drain-threat.js`). A buffer that falls
541
+ * without that threat moves nothing.
542
+ *
543
+ * THE LEVERS, in order: another limit of the height on their screen (roadmap
544
+ * item 97, step 12), then a lower height, asked of their player as URGENT —
545
+ * their page switches as soon as the rung is ready, without waiting for a
546
+ * cushion that is shrinking. Where neither can be prepared they stay where
547
+ * they are, with no message: what is on screen goes on being delivered, and
548
+ * a buffer that runs dry is filled again before the picture moves.
549
+ *
550
+ * @param {HlsSession} session - The output on their screen.
551
+ * @param {string} consumerId
552
+ * @param {number} now
553
+ * @returns {Promise<boolean>} True when a move was started or asked for.
554
+ */
555
+ async #checkViewerLink(session, consumerId, now) {
556
+ if (!this.#onScreenHere(session, consumerId)) {
557
+ return false;
558
+ }
559
+ const report = this.#host.linkReportOf(session, consumerId);
560
+ if (!report) {
561
+ return false; // their link has not been measured: no ground to move them
562
+ }
563
+ const observed = await this.observedStreamMbps(session);
564
+ if (observed === null) {
565
+ return false; // not enough produced material to compare against
566
+ }
567
+ const buffer = this.#host.bufferOf(session, consumerId, this.#host.segmentDurationSec);
568
+ // How long another output of the mode on their screen has been seen taking
569
+ // to be ready here (roadmap item 97, step 14), and otherwise this host's
570
+ // time to a first segment. The observation refines WHEN a move is started;
571
+ // what the move may be — admission, the link, the viewer's mode — is
572
+ // decided below exactly as without it.
573
+ const observedMs = this.#host.observedPreparationMs?.(session) ?? null;
574
+ const expectedMs = Number.isFinite(observedMs) ? observedMs : (this.#host.expectedFirstSegmentMs?.() ?? null);
575
+ const { threat, secondsToEmpty } = drainThreat({
576
+ bufferedSec: buffer?.bufferedSec ?? 0,
577
+ slope: buffer?.slope ?? null,
578
+ reportGapSec: buffer?.reportGapSec ?? 0,
579
+ secondsToReady: Number.isFinite(expectedMs) && expectedMs >= 0 ? expectedMs / 1000 : null
580
+ });
581
+ const carries = report.linkMbps * LINK_SAFETY >= observed;
582
+ if (carries && !threat) {
583
+ return false;
584
+ }
585
+ // Whatever else happens, a step UP prepared for them is not what they need.
586
+ this.#dropUpAsk(session, consumerId, "their buffer is draining or their link does not carry the stream");
587
+ if (this.#host.sameHeightSwitchDirection(consumerId) === "up") {
588
+ this.#host.cancelSameHeightSwitch(consumerId, "their buffer is draining or their link does not carry the stream");
589
+ }
590
+ if (carries || !threat) {
591
+ return false;
592
+ }
593
+ if (this.#host.sameHeightSwitchPending(consumerId)) {
594
+ return false; // a move down is already being prepared for them
595
+ }
596
+ const reasonText =
597
+ `link=${report.linkMbps.toFixed(2)}Mbps stream=${observed.toFixed(2)}Mbps ` +
598
+ `buffer=${(buffer?.bufferedSec ?? 0).toFixed(1)}s empty in ${secondsToEmpty === null ? "?" : secondsToEmpty.toFixed(1)}s ` +
599
+ `for ${consumerId}`;
600
+ const move = await this.#host.prepareSameHeightSwitch(session, consumerId, "down", `viewer-link-bound ${reasonText}`);
601
+ if (move.started) {
602
+ return true;
603
+ }
604
+ logger.info(`[budget] transcode ${session.id} ${reasonText}: no lower limit to move to (${move.reason})`);
605
+ const base = this.#host.outputs.pictureOf(session);
606
+ if (this.#askLowerHeight(session, `viewer-link-bound ${reasonText}`, [consumerId], {
607
+ urgent: true,
608
+ cap: this.#visibleCapOf(base, consumerId)
609
+ })) {
610
+ return true;
611
+ }
612
+ logger.info(
613
+ `[budget] transcode ${session.id} ${reasonText}: nothing smaller can be prepared; ` +
614
+ `the viewer stays on what they are given`
615
+ );
616
+ return false;
617
+ }
618
+
619
+ /**
620
+ * The picture this viewer sees against the height they are given (roadmap
621
+ * item 98).
622
+ *
623
+ * A re-encode taller than the picture they see is moved down to a rung of
624
+ * the right height — but only onto one that is READY, the piece they will
625
+ * ask for next closed on it; their page then switches once they hold the
626
+ * cushion this file needs. With no such rung ready, nothing is started: the
627
+ * next judgement of their link or of the machine takes the bound into
628
+ * account (`#askLowerHeight`).
629
+ *
630
+ * A picture shorter than the one they see is moved up one rung, in the
631
+ * background, when the machine and their link have room; the request is
632
+ * dropped if that room goes.
633
+ *
634
+ * A copy of the source is left alone whatever its height: it is never
635
+ * re-encoded for being taller than the picture on screen.
636
+ *
637
+ * @param {HlsSession} session - The output on their screen.
638
+ * @param {string} consumerId
639
+ * @param {number} now
640
+ * @returns {void}
641
+ */
642
+ #checkVisiblePicture(session, consumerId, now) {
643
+ if (!session.spec.transcodesVideo || !this.#onScreenHere(session, consumerId)) {
644
+ return;
645
+ }
646
+ const base = this.#host.outputs.pictureOf(session);
647
+ const cap = this.#visibleCapOf(base, consumerId);
648
+ if (cap === null || !this.#host.outputs.publishesVariants(base)) {
649
+ return;
650
+ }
651
+ const current = this.#host.outputs.variantHeightOf(session);
652
+ const offered = this.#host.qualityOffer.offeredHeights(base);
653
+ if (current > cap) {
654
+ const target = this.#host.outputs.splicableHeights(base)
655
+ .find((height) => height <= cap && offered.includes(height));
656
+ if (target === undefined || !this.#host.heightReadyFor(base, consumerId, target)) {
657
+ return;
658
+ }
659
+ this.#askQualityHeight(base, target, `the picture they see (${cap}p) is smaller than ${current}p`, [consumerId]);
660
+ return;
661
+ }
662
+ if (current < cap) {
663
+ const higher = this.#host.qualityOffer.nextHeightUp(base, current);
664
+ const room = this.#roomToSpare(session, now).includes(consumerId);
665
+ if (higher === undefined || higher > cap || !room || !this.#linkAdmitsHeight(base, session, consumerId, higher)) {
666
+ return;
667
+ }
668
+ this.#askQualityHeight(base, higher, `the picture they see (${cap}p) is larger than ${current}p`, [consumerId]);
669
+ }
670
+ }
671
+
672
+ /**
673
+ * The height a re-encode is bounded by for this viewer, from the picture
674
+ * they see, or null when their page has not said.
675
+ *
676
+ * @param {HlsSession} base
677
+ * @param {string} consumerId
678
+ * @returns {number | null}
679
+ */
680
+ #visibleCapOf(base, consumerId) {
681
+ return visibleHeightCap(base.file.width, base.file.height, this.#host.visiblePictureOf(base, consumerId));
682
+ }
683
+
684
+ /**
685
+ * Let go of a request to move this viewer UP, if one stands.
686
+ *
687
+ * @param {HlsSession} session
688
+ * @param {string} consumerId
689
+ * @param {string} because
690
+ * @returns {void}
691
+ */
692
+ #dropUpAsk(session, consumerId, because) {
693
+ const base = this.#host.outputs.pictureOf(session);
694
+ const ask = this.#host.standingAskOf(base, consumerId);
695
+ const onScreen = this.#host.stepOnScreenOf(base, consumerId);
696
+ const current = this.#host.outputs.variantHeightOf((onScreen ? this.#host.outputs.get(onScreen) : null) ?? base);
697
+ if (ask && ask.height > current) {
698
+ this.#host.dropAskOf(base, consumerId);
699
+ logger.info(`[budget] transcode ${base.id} no longer asks ${consumerId} for ${ask.height}p: ${because}`);
700
+ }
701
+ }
702
+
703
+ /**
704
+ * Whether this output is the one on this viewer's screen.
705
+ *
706
+ * A viewer is registered on the picture for as long as they watch any step
707
+ * of it, so being present on an output does not mean watching it. What an
708
+ * output measures — its stream, its speed — is about the people who have it
709
+ * on screen, and a decision about a viewer's link is taken against the
710
+ * output they actually receive.
711
+ *
712
+ * @param {HlsSession} session
713
+ * @param {string} consumerId
714
+ * @returns {boolean}
715
+ */
716
+ #onScreenHere(session, consumerId) {
717
+ const base = this.#host.outputs.pictureOf(session);
718
+ const onScreen = this.#host.stepOnScreenOf(base, consumerId);
719
+ return (onScreen ?? base.id) === session.id;
720
+ }
721
+
722
+ /**
723
+ * Observed produced bitrate (Mbit/s) averaged over the last few COMPLETED
724
+ * segment files (the newest file may still be being written and is
725
+ * excluded). Transcode sessions only — their segment grid is uniform, so
726
+ * bytes / (count × segDur) is exact. Returns null when there is not enough
727
+ * material to measure.
728
+ *
729
+ * @param {HlsSession} session
730
+ * @returns {Promise<number | null>}
731
+ */
732
+ async observedStreamMbps(session) {
733
+ let names;
734
+ try {
735
+ names = this.#host.producedNumbers(session).map((index) => session.segmentFormat.segmentFileName(index));
736
+ } catch {
737
+ return null;
738
+ }
739
+ const indices = [];
740
+ for (const name of names) {
741
+ const index = session.segmentFormat.segmentIndexFromName(name);
742
+ if (index >= 0) {
743
+ indices.push(index);
744
+ }
745
+ }
746
+ if (indices.length < 3) {
747
+ return null; // need ≥2 completed segments after dropping the newest
748
+ }
749
+ indices.sort((a, b) => a - b);
750
+ const completed = indices.slice(0, -1).slice(-LINK_OBSERVED_SEGMENTS);
751
+ let bytes = 0;
752
+ try {
753
+ for (const index of completed) {
754
+ const segmentPath = this.#host.segmentStore.pathOf(session.outputKey ?? "", index);
755
+ if (!segmentPath) {
756
+ break;
757
+ }
758
+ const st = await stat(segmentPath);
759
+ bytes += st.size;
760
+ }
761
+ } catch {
762
+ return null; // a segment vanished mid-measure (seek-restart cleanup)
763
+ }
764
+ return (bytes * 8) / (completed.length * this.#host.segmentDurationSec) / 1e6;
765
+ }
766
+
767
+ /**
768
+ * Decide whether a sustained sub-realtime transcode is limited by the encoder
769
+ * (CPU) or by a download-starved input. Compares the torrent's download rate
770
+ * with the source's average byte rate; a fully-downloaded file can never be
771
+ * download-bound. Returns "cpu" | "download" | "unknown" ("unknown" is treated
772
+ * as CPU by the caller — the common case, logged as such).
773
+ *
774
+ * @param {HlsSession} session
775
+ * @returns {Promise<"cpu" | "download" | "unknown">}
776
+ */
777
+ async classifyTranscodeBound(session) {
778
+ if (!this.#host.getSourceStats) {
779
+ return "unknown";
780
+ }
781
+ let stats;
782
+ try {
783
+ stats = await this.#host.getSourceStats(session.file.sourceKey, session.file.fileIndex);
784
+ } catch {
785
+ return "unknown";
786
+ }
787
+ if (!stats) {
788
+ return "unknown";
789
+ }
790
+ // A fully (or almost fully) downloaded file cannot be download-bound.
791
+ if (typeof stats.fileProgress === "number" && stats.fileProgress >= 0.999) {
792
+ return "cpu";
793
+ }
794
+ const duration = Number.isFinite(session.file.durationSeconds) ? session.file.durationSeconds : 0;
795
+ const length = Number.isFinite(stats.fileLength) && stats.fileLength > 0 ? stats.fileLength : 0;
796
+ const downloadSpeed = Number.isFinite(stats.downloadSpeed) ? stats.downloadSpeed : 0;
797
+ if (duration <= 0 || length <= 0) {
798
+ return "unknown"; // cannot compute the source byte rate
799
+ }
800
+ const sourceByteRate = length / duration;
801
+ return downloadSpeed >= sourceByteRate * BUDGET_DOWNLOAD_OK_FACTOR ? "cpu" : "download";
802
+ }
803
+
804
+ /**
805
+ * An encoder is about to start on this output.
806
+ *
807
+ * Any start resets the cumulative `speed` ffmpeg reports, so both of this
808
+ * budget's windows over it start again: the pair of readings speed is learned
809
+ * from, and the slow window — otherwise warm-up right after a seek reads as
810
+ * sustained sub-realtime and triggers a premature step down.
811
+ *
812
+ * @param {object} output
813
+ * @returns {void}
814
+ */
815
+ noteRunStarting(output) {
816
+ const state = qualityStateOf(output);
817
+ state.learnSample = null;
818
+ state.budgetSlowSince = 0;
819
+ }
820
+
821
+ /**
822
+ * The height this proxy is asking the player to move to, or 0.
823
+ *
824
+ * Cleared the moment the viewer is on it — the request has been answered —
825
+ * and dropped when it runs out, which is the only sign this side ever gets
826
+ * that a player could not or would not follow it. A browser on a manual pick
827
+ * ignores every request by design, so an unanswered one is not an error; it
828
+ * is said once and let go, rather than repeated for the rest of the film.
829
+ *
830
+ * @param {HlsSession} named - The session the browser addressed.
831
+ * @returns {number}
832
+ */
833
+ standingAskFor(named, consumerId = "") {
834
+ const base = this.#host.outputs.pictureOf(named);
835
+ if (this.#host.qualityModeOf(base, consumerId) !== "auto") {
836
+ this.#host.dropAskOf(base, consumerId);
837
+ return 0;
838
+ }
839
+ const ask = this.#host.standingAskOf(base, consumerId);
840
+ if (!ask) {
841
+ return 0;
842
+ }
843
+ const onScreen = this.#host.stepOnScreenOf(base, consumerId);
844
+ const current = onScreen ? this.#host.outputs.get(onScreen) : base;
845
+ if (this.#host.outputs.variantHeightOf(current ?? base) === ask.height) {
846
+ this.#host.dropAskOf(base, consumerId); // this viewer is there; nothing left to ask for
847
+ return 0;
848
+ }
849
+ if (Date.now() - ask.at > QUALITY_ASK_TTL_MS) {
850
+ this.#host.dropAskOf(base, consumerId);
851
+ logger.info(
852
+ `[budget] transcode ${base.id} asked viewer ${consumerId || "unnamed"} for ${ask.height}p and the player stayed where it was ` +
853
+ `(${ask.reason}); letting the request go`
854
+ );
855
+ return 0;
856
+ }
857
+ return ask.height;
858
+ }
859
+
860
+ /**
861
+ * Whether the request standing for this viewer is urgent — their buffer
862
+ * would run dry before anything else could arrive.
863
+ *
864
+ * @param {HlsSession} named
865
+ * @param {string} [consumerId]
866
+ * @returns {boolean}
867
+ */
868
+ standingAskIsUrgent(named, consumerId = "") {
869
+ if (this.standingAskFor(named, consumerId) === 0) {
870
+ return false;
871
+ }
872
+ return this.#host.standingAskOf(this.#host.outputs.pictureOf(named), consumerId)?.urgent === true;
873
+ }
874
+
875
+ heightsOnScreen(base) {
876
+ return [...this.variantsOnScreen(base)]
877
+ .map((id) => this.#host.outputs.get(id))
878
+ .filter((member) => member)
879
+ .map((member) => this.#host.outputs.variantHeightOf(member));
880
+ }
881
+
882
+ /**
883
+ * Every session of this family that a live viewer has on screen.
884
+ *
885
+ * The question "may this rung's encoder be stopped" has no single answer once
886
+ * two viewers watch one picture at two qualities: the rung one of them left is
887
+ * the rung the other is watching. Nothing may be stopped for being left unless
888
+ * nobody is left on it.
889
+ *
890
+ * @param {HlsSession} base
891
+ * @returns {Set<string>} Session ids.
892
+ */
893
+ variantsOnScreen(base) {
894
+ const live = this.#host.liveConsumers(base);
895
+ const onScreen = new Set();
896
+ for (const consumerId of this.#host.consumersOn(base)) {
897
+ if (consumerId && live.size > 0 && !live.has(consumerId)) {
898
+ continue;
899
+ }
900
+ // No step chosen is the picture itself, which is on screen too.
901
+ onScreen.add(this.#host.stepOnScreenOf(base, consumerId) ?? base.id);
902
+ }
903
+ if (onScreen.size === 0) {
904
+ onScreen.add(base.id);
905
+ }
906
+ return onScreen;
907
+ }
908
+
909
+ /**
910
+ * The heights this session's file will be served at, largest first, and the
911
+ * two lists a file would be served at before any session exists.
912
+ *
913
+ * Both are the quality layer's answers and are computed there. What is left
914
+ * here is the door: a route holds the session manager and asks it, and these
915
+ * go the day the route can ask the layer directly.
916
+ *
917
+ * @param {HlsSession} session
918
+ * @returns {number[]}
919
+ */
920
+ offeredHeights(session) {
921
+ return this.#host.qualityOffer.offeredHeights(session);
922
+ }
923
+
924
+ /**
925
+ * @param {object} mediaInfo
926
+ * @returns {{ copy: number[], transcode: number[] } | null}
927
+ */
928
+ predictOfferedHeights(mediaInfo) {
929
+ return this.#host.qualityOffer.predictOfferedHeights(mediaInfo);
930
+ }
931
+ }