@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,745 @@
1
+ /**
2
+ * @file Which output answers a request for a file, made if it is not here yet.
3
+ *
4
+ * A request names a file, the tracks wanted and a size; what answers it is an
5
+ * OUTPUT, and deciding which is the encoding component's: the arrangement of
6
+ * the sound, the cut grid, the format the budget settles on, and whether an
7
+ * output already here serves the request instead. Two requests whose outputs
8
+ * agree ARE one output. Who asked is not a parameter: placing the requester on
9
+ * the output is the server operation's business (`server/ViewerRequests.js`),
10
+ * and nothing about a viewer enters what is decided here.
11
+ *
12
+ * What the file says about itself is read by the media component and handed in
13
+ * (`probeMediaInfo`, `probeKeyframeTimes`), as is everything else this reads.
14
+ */
15
+
16
+ import { createRequire } from "node:module";
17
+ import { buildResolutionLadder, chooseOutputFps } from "./hwaccel.js";
18
+ import { resolveSegmentFormat, SEGMENT_FORMAT_IDS } from "./segment-formats/index.js";
19
+ import { AudioOutput, CutGrid, OUTPUT_NO_CAPACITY, OUTPUT_UNAVAILABLE, OutputSpec, VideoOutput } from "./output/index.js";
20
+ import { Timeline, Timelines } from "./output/Timeline.js";
21
+ import { computeCutGrid } from "./output/cut-grid.js";
22
+ import { Output } from "./output/Output.js";
23
+ import { mediaPlaylistText } from "./output/playlists.js";
24
+ import { formatSeconds } from "./EncodeRuns.js";
25
+ import { EncodedOutput } from "./output/EncodedOutput.js";
26
+ import { decideOutputFormat } from "./quality/output-format.js";
27
+ import { rungForVisiblePicture } from "./quality/visible-rung.js";
28
+ import { audioLoadOf, linkAnswerFigures as linkFiguresOf } from "./quality/link-budget.js";
29
+ import { AUDIO_TRANSCODE_KBPS } from "./args.js";
30
+
31
+
32
+ /** Own package version, stamped onto output-start log lines. */
33
+ const PROXY_VERSION = createRequire(import.meta.url)("../../package.json").version;
34
+
35
+ export class OutputOpening {
36
+ /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
37
+ #host;
38
+
39
+ /**
40
+ * @param {object} host - `logger`, `probeMediaInfo`, `probeKeyframeTimes`, `enabled`, `segmentFormat`, `renditions`, `sourceFiles`, `getCachedMediaInfo`, `localBaseUrl`, `tonemapSupported`, `videoEncoder`, `hostLoad`, `keyframeTables`, `timelines`, `segmentDurationSec`, `softwarePresetBenchmark`, `decodeCostModel`, `encodeCost`, `outputs`, `segmentStore`, `hostTimings`, `returns`, `encodeRuns`
41
+ */
42
+ constructor(host) {
43
+ this.#host = host;
44
+ }
45
+
46
+ /**
47
+ * The box a re-encoded picture is fitted into.
48
+ *
49
+ * A box the request names is the box (a quality step names its height). With
50
+ * none named, the picture the viewer sees decides: the smallest rung of the
51
+ * source's ladder whose frame is not smaller than it (roadmap item 98). With
52
+ * neither, zeroes — the source's own size.
53
+ *
54
+ * @param {{ normalizedTargetWidth: number, normalizedTargetHeight: number, visiblePicture: { width: number, height: number } | null, sourceWidth: number, sourceHeight: number }} params
55
+ * @returns {{ width: number, height: number }}
56
+ */
57
+ #targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }) {
58
+ if (normalizedTargetWidth > 0 || normalizedTargetHeight > 0) {
59
+ return { width: normalizedTargetWidth, height: normalizedTargetHeight };
60
+ }
61
+ const rung = rungForVisiblePicture(
62
+ buildResolutionLadder(Math.round(Number(sourceWidth) || 0), Math.round(Number(sourceHeight) || 0)),
63
+ visiblePicture
64
+ );
65
+ return rung ? { width: rung.width, height: rung.height } : { width: 0, height: 0 };
66
+ }
67
+
68
+ /**
69
+ * Ask the requester's call whether they may be put on this output, and throw
70
+ * the refusal the way the route answers it.
71
+ *
72
+ * @param {((output: object) => { admitted: boolean, reason: string, speedX: number | null }) | null} claim
73
+ * @param {object} output
74
+ * @param {string} logName
75
+ * @returns {void}
76
+ */
77
+ #claimOrRefuse(claim, output, logName) {
78
+ if (typeof claim !== "function") {
79
+ return;
80
+ }
81
+ const answer = claim(output);
82
+ if (answer?.admitted) {
83
+ return;
84
+ }
85
+ const reason = answer?.reason || "this machine has no place for one more encoder";
86
+ this.#host.logger.info(`transcode "${logName}": not opened for this viewer — ${reason} (key=${output.outputKey})`);
87
+ const error = new Error(`This proxy cannot take this video now: ${reason}.`);
88
+ error.code = OUTPUT_NO_CAPACITY;
89
+ error.details = {
90
+ reason,
91
+ figures: { speedX: Number.isFinite(answer?.speedX) ? Number(answer.speedX.toFixed(3)) : null, outputKey: output.outputKey }
92
+ };
93
+ throw error;
94
+ }
95
+
96
+ /**
97
+ * The output that answers this request: one already here, or one made now.
98
+ * No encoder is started here — where encoders go is the plan's.
99
+ *
100
+ * Throws with `error.code === "TRANSCODE_DISABLED"` when transcoding is
101
+ * disabled on this proxy instance.
102
+ *
103
+ * @param {object} options
104
+ * @param {string} options.sourceKey - Registry source key.
105
+ * @param {number} options.fileIndex - Zero-based file index in the torrent.
106
+ * @param {boolean} [options.transcodeVideo=false]
107
+ * @param {boolean} [options.transcodeAudio=false]
108
+ * @param {string} [options.fileName=""] - Display name for log output.
109
+ * @param {number} [options.targetWidth=0] - Target video width (0 = keep source).
110
+ * @param {number} [options.targetHeight=0] - Target video height (0 = keep source).
111
+ * @param {number} [options.startPositionSeconds=0] - Seek start position in seconds.
112
+ * @param {number} [options.audioTrackIndex=0] - Type-relative audio track to map (0:a:N).
113
+ * @param {boolean} [options.exactSize=false] - Produce the target box exactly (capped to source), with no budget downscale and no runtime downswitch. Says nothing about who asked: every rung of a master sets it.
114
+ * @param {number | null} [options.capKbps=null] - Nominal bitrate limit in kbit/s; null for the size's own. Above the size's own it is refused.
115
+ * @param {{ width: number, height: number } | null} [options.visiblePicture=null] - The picture as the requesting viewer sees it, in physical pixels. With no target box given, a re-encoded picture's box is the smallest rung whose frame is not smaller than this (roadmap item 98).
116
+ * @returns {Promise<{ output: EncodedOutput, existed: boolean, audio: { trackIndex: number, transcode: boolean }, verdict: object | null }>}
117
+ */
118
+ async open({
119
+ sourceKey,
120
+ fileIndex,
121
+ transcodeVideo = false,
122
+ transcodeAudio = false,
123
+ fileName = "",
124
+ targetWidth = 0,
125
+ targetHeight = 0,
126
+ startPositionSeconds = 0,
127
+ audioTrackIndex = 0,
128
+ exactSize = false,
129
+ // The caller takes its audio from a rendition group, so the picture is
130
+ // encoded without it and each audio track is encoded once for the file
131
+ // instead of once per rung. Off unless asked for: a browser that does not
132
+ // know about renditions must still get its audio in the stream.
133
+ audioRenditions = false,
134
+ // This session IS one of those renditions: one audio track, no picture, cut
135
+ // on the same grid as the video it accompanies.
136
+ audioOnly = false,
137
+ // The arrangement decided by the session this one belongs to — a variant or
138
+ // a rendition of it. Every session of one master must agree about where the
139
+ // audio is, and only the base is in a position to decide: a variant asked on
140
+ // its own would answer about the rungs IT would be offered at, which is a
141
+ // different list. Null means "decide it here", which is what a base does.
142
+ inheritedAudioSeparate = null,
143
+ segmentFormatId = "",
144
+ // The cut grid of the session this one is a quality variant of: its
145
+ // keyframe times and which container they were read from. Present only for
146
+ // a variant of a session cut at the source's keyframes, and it is what
147
+ // makes the two interchangeable.
148
+ inheritedGrid = null,
149
+ // "manual" when the viewer chose this size by hand, "auto" when it is the
150
+ // automatic choice; left out, a size produced exactly counts as chosen by
151
+ // hand. Decides whether an output already here may serve them instead.
152
+ servingMode = null,
153
+ // What the requesting viewer's link measured, or null.
154
+ viewerLinkMbps = null,
155
+ // The nominal bitrate limit asked for, in kbit/s, or null for the size's
156
+ // own. Part of the output's identity: another limit is another output.
157
+ capKbps = null,
158
+ // The soundtrack THIS viewer receives with the picture — from this output
159
+ // or beside it — as `{ transcode, bitrateKbps }`. Left out, the one this
160
+ // request names is theirs. A step opened on a viewer's behalf passes the
161
+ // track they chose, which need not be the one the picture was opened with.
162
+ viewerAudio = undefined,
163
+ visiblePicture = null,
164
+ // WHETHER THE REQUESTER MAY BE PUT ON THE OUTPUT, and putting them there,
165
+ // in one synchronous call (roadmap item 97, step 14). Called with the
166
+ // output the moment it answers the request — a new one registered, or one
167
+ // already here — and before anything else can run, so that the place it
168
+ // takes on this machine is counted before the next opening is asked.
169
+ // Returns `{ admitted, reason, speedX }`; a refusal is thrown as
170
+ // OUTPUT_NO_CAPACITY and a new output made for it is withdrawn. Who the
171
+ // requester is stays with the caller: this is handed an opaque call.
172
+ // Absent — a step or a soundtrack opened on a viewer's behalf, whose place
173
+ // the preparation already holds — nothing is asked.
174
+ claim = null
175
+ }) {
176
+ if (!this.#host.enabled) {
177
+ const error = new Error("Audio transcoding is disabled on this proxy.");
178
+ error.code = "TRANSCODE_DISABLED";
179
+ throw error;
180
+ }
181
+
182
+ // The container is the viewer's to choose, because the viewer's browser is
183
+ // what has to decode the result and only it knows what its media stack
184
+ // accepts. A copied MP3 track is the case that forced this: hls.js demuxes
185
+ // MPEG-TS itself and hands raw MP3 to an `audio/mpeg` buffer, which every
186
+ // browser supports, while an fMP4 segment goes to MSE untouched and
187
+ // `audio/mp4; codecs="mp3"` is refused — measured false in Chromium, where
188
+ // `canPlayType` cheerfully answers "probably". Same file, same browser:
189
+ // plays as MPEG-TS, silent loop as fMP4. The proxy's `--segment-format`
190
+ // stays the default for a client that expresses no preference.
191
+ // An unrecognised value falls back to the operator's choice rather than to
192
+ // the library default — `resolveSegmentFormat` cannot tell the two apart,
193
+ // and this value arrives from a client.
194
+ const segmentFormat = SEGMENT_FORMAT_IDS.includes(segmentFormatId)
195
+ ? resolveSegmentFormat(segmentFormatId)
196
+ : this.#host.segmentFormat;
197
+
198
+ const normalizedTargetWidth = Number.isInteger(targetWidth) && targetWidth > 0 ? targetWidth : 0;
199
+ const normalizedTargetHeight = Number.isInteger(targetHeight) && targetHeight > 0 ? targetHeight : 0;
200
+ // Round seek position to the nearest 10 s so that two consumers seeking
201
+ // to similar positions can share the same ffmpeg session.
202
+ const normalizedStartPosition =
203
+ Number.isFinite(startPositionSeconds) && startPositionSeconds > 0
204
+ ? Math.round(startPositionSeconds / 10) * 10
205
+ : 0;
206
+ const normalizedAudioTrack =
207
+ Number.isInteger(audioTrackIndex) && audioTrackIndex > 0 ? audioTrackIndex : 0;
208
+ // What the requester wants of the sound, handed back so the viewer who
209
+ // asked can be told apart from another viewer of the same output.
210
+ const audio = { trackIndex: normalizedAudioTrack, transcode: transcodeAudio === true };
211
+ // Which FILE the chosen soundtrack lives in, and which track it is inside
212
+ // that file. A release often ships its dub as a file of its own beside the
213
+ // picture, and the number that travels between the browser, this route and
214
+ // the `a/<n>/` address is flat across both — see `audio-inventory.js`. This
215
+ // is the one place that resolves it, so nothing downstream carries two
216
+ // vocabularies.
217
+ const audioSource = this.#host.renditions.resolveAudioSource(sourceKey, fileIndex, normalizedAudioTrack);
218
+ // The file itself, held once for every session of it. Its name, its key and
219
+ // the facts a probe of it returned used to be copied onto each session, so
220
+ // two viewers of one film held two copies of numbers that cannot differ —
221
+ // and twenty places assembled its key by hand to reach the caches that are
222
+ // keyed by a file.
223
+ const file = this.#host.sourceFiles.get(sourceKey, fileIndex, fileName);
224
+ const forceExactSize = exactSize === true && transcodeVideo;
225
+ // Whether this output carries its sound at all — decided HERE, before the
226
+ // key, and never derived a second time.
227
+ //
228
+ // It used to be settled after the session had already been put in the map,
229
+ // which was survivable only while the key carried the audio parameters
230
+ // unconditionally: the key could say "no sound in this output" while the
231
+ // output muxed it, and two viewers who chose different languages would then
232
+ // have shared one encode and one of them would have heard the other's.
233
+ const audioSeparate = inheritedAudioSeparate === null
234
+ ? this.#host.renditions.audioTravelsSeparately({
235
+ sourceKey,
236
+ fileIndex,
237
+ audioRenditions,
238
+ // The rung this session will be NAMED by. The budget may still
239
+ // downscale the encode below it, and that cannot change the answer:
240
+ // what it picks is a rung of the same ladder, already in the set.
241
+ ownHeight: normalizedTargetHeight
242
+ })
243
+ : inheritedAudioSeparate === true;
244
+ // A rendition IS the sound, so it carries it whatever the arrangement says;
245
+ // a picture carries it only when the browser is not taking it separately.
246
+ const carriesAudio = audioOnly === true || !audioSeparate;
247
+ const carriesVideo = audioOnly !== true;
248
+ const createEntryMs = Date.now();
249
+ // The directory belongs to the OUTPUT, not to this session: two sessions
250
+ // whose parameters agree produce interchangeable segments, so they write
251
+ // into one place and each serves what the other has already made. The start
252
+ // position is deliberately not part of it — segment 42 covers the same span
253
+ // whoever began where.
254
+ // The file this session's encoder READS. A soundtrack shipped as its own
255
+ // file is encoded FROM that file, and an audio rendition carries nothing
256
+ // else — so it reads the sidecar directly and needs no second input at all.
257
+ // The muxed case, where a browser takes its audio inside the picture's own
258
+ // stream, is the one that reads two files.
259
+ //
260
+ // Which of the two this is used to be a boolean on the session
261
+ // (`readsSidecarAlone`) beside a string URL built from it. It is the same
262
+ // statement as "the file it reads is not the file of the picture", so it is
263
+ // that comparison now and there is nothing to keep in step.
264
+ const audioFile = this.#host.sourceFiles.get(sourceKey, audioSource.fileIndex, audioSource.name);
265
+ const inputFile = audioOnly === true && audioSource.isSidecar ? audioFile : file;
266
+ // Media info (duration/resolution/fps/startTime/HDR) up front, so we can
267
+ // serve a complete VOD playlist (#EXT-X-ENDLIST) with the correct total
268
+ // duration and a fully seekable timeline before a single segment exists.
269
+ // Reuse the planner's probe when it is available and complete — the plan
270
+ // request just ran the same ffmpeg scan over the same input. Fall back to
271
+ // a fresh probe otherwise (proxy restarted between plan and session, or a
272
+ // critical field is missing).
273
+ const mediaInfoStartMs = Date.now();
274
+ const cachedMediaInfo = this.#host.getCachedMediaInfo?.({ sourceKey, fileIndex }) ?? null;
275
+ const cachedUsable =
276
+ cachedMediaInfo &&
277
+ Number.isFinite(cachedMediaInfo.durationSeconds) &&
278
+ cachedMediaInfo.durationSeconds > 0 &&
279
+ Number.isFinite(cachedMediaInfo.width) &&
280
+ cachedMediaInfo.width > 0 &&
281
+ Number.isFinite(cachedMediaInfo.height) &&
282
+ cachedMediaInfo.height > 0;
283
+ // Always the PICTURE's, even when this session reads a soundtrack from
284
+ // another file: the timeline, the duration and the cut grid are the
285
+ // picture's, and a rendition exists to be played WITH it. Only where the
286
+ // sidecar's own timeline begins is read from the sidecar, just below.
287
+ // No session id on it: this read is a probe of the picture, not this
288
+ // session's own delivery, and counting it against the session would tell a
289
+ // waiting browser that its film is arriving when what arrived was a header.
290
+ const pictureUrl = file.streamUrl(this.#host.localBaseUrl);
291
+ const mediaInfo = cachedUsable
292
+ ? cachedMediaInfo
293
+ : await this.#host.probeMediaInfo(pictureUrl.toString());
294
+ const mediaInfoMs = Date.now() - mediaInfoStartMs;
295
+ const mediaInfoSource = cachedUsable ? "cached" : "probed";
296
+ // The file takes in what the probe said. It is the same answer for every
297
+ // session of this file — a quality step, a soundtrack, a second viewer — so
298
+ // it is kept once instead of being copied into each. A later session with a
299
+ // fresher reading updates it: on a cold torrent the first probe can come
300
+ // back without a duration, and the second is the one that has it.
301
+ file.learn(mediaInfo);
302
+ const durationSeconds = file.durationSeconds ?? 0;
303
+ const sourceWidth = file.width;
304
+ const sourceHeight = file.height;
305
+ const sourceStartTime = file.startTime;
306
+ // Where the timeline of a soundtrack shipped as its own file begins.
307
+ //
308
+ // A soundtrack in another file has a start time of its own, and it is the
309
+ // one that must be subtracted when the output is relabelled onto a
310
+ // zero-based timeline: subtract the picture's instead and the sound sits at
311
+ // a fixed offset from it for the whole film. Read from the file rather than
312
+ // assumed to be zero, because assuming it is exactly the fault being
313
+ // avoided.
314
+ //
315
+ // NOT awaited. Creating a session used to stop here until the answer came
316
+ // back, and on a cold start the answer needs the sidecar's header off the
317
+ // swarm — 8121 ms of every session created, measured three times out of
318
+ // three on 2026-09-03. What is known now is used now, and the reading runs
319
+ // behind; when it lands it lands on the FILE, which every session of that
320
+ // soundtrack shares, so the spawn path sees it without re-reading anything.
321
+ //
322
+ // Unknown means "no difference between the two timelines", not "the
323
+ // soundtrack starts at zero". The shift exists to correct a difference
324
+ // between two containers; asserting one that has not been read is inventing
325
+ // a number, while assuming none leaves the sound exactly where a release
326
+ // remuxed from a single source puts it.
327
+ if (audioSource.isSidecar) {
328
+ this.#host.renditions.warmFileStartTime(audioFile);
329
+ }
330
+ // Tone-map an HDR source to SDR only when re-encoding video on the software
331
+ // path and this ffmpeg has the filters. Hardware encoders keep their own
332
+ // (untone-mapped) path for now; when unavailable, HDR falls back to a plain
333
+ // 8-bit convert (washed-out but playable).
334
+ const applyTonemap =
335
+ transcodeVideo === true &&
336
+ mediaInfo.isHdr === true &&
337
+ this.#host.tonemapSupported &&
338
+ this.#host.videoEncoder?.kind === "software";
339
+ // Output frame rate inherited from the source (integer, capped) so 25/30
340
+ // fps content is not resampled to 24. Fixed-GOP encoders keep the fps↔GOP
341
+ // relationship exact; time-based-keyframe encoders just use it as the rate.
342
+ const outputFps = chooseOutputFps(mediaInfo.fps);
343
+ const hasDuration = Number.isFinite(durationSeconds) && durationSeconds > 0;
344
+ const logName = file.name;
345
+
346
+ // Size the reader's window in seconds of playback rather than bytes. Needs
347
+ // the file's own average byte rate, which is size ÷ duration; the size
348
+ // comes from the same stats call the realtime budget uses. Best effort —
349
+ // without it the reader keeps its own byte default.
350
+ //
351
+ // Sized for the file being READ, which for a soundtrack shipped separately
352
+ // is that file: it is a twentieth of the picture's size over the same
353
+ // duration, so the picture's byte rate would buy a window twenty times
354
+ // wider than the seconds it is meant to represent, and the piece store
355
+ // would hold it.
356
+ const readWindowBytes = await this.#host.hostLoad.readWindowBytesFor(
357
+ inputFile.sourceKey,
358
+ inputFile.fileIndex,
359
+ durationSeconds
360
+ );
361
+ if (!hasDuration) {
362
+ this.#host.logger.warn(
363
+ `transcode "${logName}": could not probe duration; falling back to ` +
364
+ "ffmpeg-managed (growing) playlist"
365
+ );
366
+ }
367
+
368
+ // For the video-copy path we cannot insert keyframes, so the playlist's
369
+ // segment boundaries must match the source's real keyframes (otherwise the
370
+ // player sees gaps on seek). Re-encoded video uses a uniform grid for
371
+ // segment boundaries instead (its fixed GOP makes the cuts land there —
372
+ // computeSegmentBoundaries ignores keyframeTimes when transcodeVideo).
373
+ //
374
+ // But the probe is ALSO used for something both branches need: choosing a
375
+ // SOURCE seek position ffmpeg can actually land on. `-ss` before `-i` trusts
376
+ // the container's own on-the-fly seek/index, which for some containers
377
+ // (observed: AVI with VBR MP3 audio) can point at a position with no valid
378
+ // frame boundary at all — ffmpeg then fails outright ("Seek failed" /
379
+ // "Header missing"), not just imprecisely. Snapping the seek to the nearest
380
+ // KNOWN real keyframe (see #startEncodeRun) avoids that. So probe for both
381
+ // branches; on failure both fall back to their current behaviour (uniform
382
+ // grid for boundaries, raw target for seeking) — no regression.
383
+ // The file's own table — the object every reader of this file holds, so a
384
+ // read that answers after this session was made still reaches it.
385
+ const keyframes = this.#host.keyframeTables.of({ sourceKey, fileIndex });
386
+ let keyframeMs = -1; // -1 = not run (skipped), -2 = running in the background
387
+ // A quality variant of a session whose cuts are the source's keyframes must
388
+ // be cut at exactly those same times, or its segments cannot stand where
389
+ // the other's would have. Nothing has to be handed over for that: the table
390
+ // is the FILE's, and a variant is a session of the same file, so it reads
391
+ // the one answer. What the inherited grid still carries is the CORRECTED
392
+ // boundaries and the published playlist, which are properties of the family
393
+ // rather than of the file.
394
+ if (inheritedGrid) {
395
+ // Nothing to read: the table above IS the file's, corrections included.
396
+ } else if (hasDuration && !transcodeVideo && !audioOnly) {
397
+ // Video-COPY path: the keyframe times are REQUIRED to build correct
398
+ // segment boundaries (the playlist itself), so this MUST block session
399
+ // creation — an incorrect playlist is worse than a slower start.
400
+ //
401
+ // The wait is bounded, and the bound is what the read costs on a real
402
+ // host rather than a figure picked here (`KEYFRAME_TABLE_BUDGET_MS`). A
403
+ // comment in this place used to promise a short timeout and "never more
404
+ // than ~6 s to session start" when no timeout existed at all; the file
405
+ // comes off a torrent, so the bytes the table lives in may still be
406
+ // arriving, and a session used to wait for them without limit.
407
+ //
408
+ // What is read is the container's OWN table (Cues/stss) rather than a
409
+ // scan of the media. On the copy path ffmpeg can only cut at the source's
410
+ // existing keyframes, so these times ARE the segment boundaries —
411
+ // declaring an even grid instead is a falsehood the player punishes: it
412
+ // walks the whole file to rebuild the timeline, or presents audio with no
413
+ // picture because a segment starts with nothing decodable (both
414
+ // field-observed 2026-08-02). Scanning cannot supply them here — the file
415
+ // comes off a torrent, and a full packet scan of 5.5 GB found 77
416
+ // keyframes in 45 s without finishing, while the container index yields
417
+ // all 570 in 0.8 s from two point reads (16 KB).
418
+ const keyframeStartMs = Date.now();
419
+ const { arrived } = await this.#host.keyframeTables.within({ sourceKey, fileIndex, logName });
420
+ keyframeMs = Date.now() - keyframeStartMs;
421
+ if (!arrived) {
422
+ // A read that ran out of its budget is still running, and the table is
423
+ // still unanswered — which is not the same as a file with no keyframes,
424
+ // and the distinction is the table's own (`answered` against
425
+ // `readable`). Recorded as an absence it would make a passing shortage
426
+ // of bytes look like a property of the bytes, and every later session
427
+ // of the file would re-encode a picture that can be copied.
428
+ this.#host.logger.warn(
429
+ `transcode: the keyframe table for "${logName}" has not arrived in ` +
430
+ `${Math.round(this.#host.keyframeTables.budgetMs / 1000)}s, so this session re-encodes the picture ` +
431
+ "instead of copying it; the read goes on and the next session of this file gets the copy"
432
+ );
433
+ }
434
+ if (!keyframes.readable) {
435
+ // No index, so there is no honest grid for a COPY: a copied picture can
436
+ // only be cut at the source's own keyframes, and we do not know where
437
+ // they are. Declaring an even grid instead is a falsehood the player
438
+ // punishes — it walks the whole file to rebuild the timeline, or shows
439
+ // audio with no picture because a segment begins with nothing
440
+ // decodable (both field-observed 2026-08-02).
441
+ //
442
+ // Re-encoding is the honest answer and costs an encoder: keyframes are
443
+ // then PLACED at our own cut times rather than found, so the grid is
444
+ // correct by construction whatever the container. MPEG-TS is the case
445
+ // this exists for — measured 2026-08-21, 669 real keyframes and no
446
+ // index of any kind to read them from — and a container whose index
447
+ // could not be read in the budget lands here too, which is right for
448
+ // the same reason.
449
+ transcodeVideo = true;
450
+ if (keyframes.answered) {
451
+ this.#host.logger.warn(
452
+ `transcode: no keyframe index in the ${keyframes.format} container for ` +
453
+ `"${logName}" — a copied picture has no honest grid without one, so the video is ` +
454
+ "re-encoded instead and its keyframes are placed on our own cuts"
455
+ );
456
+ }
457
+ }
458
+ } else if (hasDuration && transcodeVideo) {
459
+ // Re-encode path: keyframeTimes are ONLY used to snap a LATER seek (see
460
+ // #startEncodeRun) — segment boundaries stay on the uniform grid either
461
+ // way. So this does NOT need to block session creation / the first
462
+ // segment's start. Run it in the background with a FULL budget instead of
463
+ // the 6 s cap: AVI-class containers need a full packet scan, which 6 s can
464
+ // never afford without delaying playback start — that starved budget is
465
+ // exactly why the probe kept missing on the container where the seek bug
466
+ // was field-diagnosed. A run reads the file's table on every call, so a
467
+ // seek that happens AFTER this finishes picks it up automatically; one
468
+ // that happens before falls back to the existing circuit breaker as a
469
+ // safety net (no regression either way).
470
+ keyframeMs = -2;
471
+ const backgroundStartedAt = Date.now();
472
+ void this.#host.probeKeyframeTimes(inputFile.streamUrl(this.#host.localBaseUrl).toString(), 25_000).then((times) => {
473
+ // Into the FILE's table, which the picture, its quality steps and a
474
+ // second viewer's session all hold — so nothing has to be alive for the
475
+ // answer to be kept, and the session this probe was started for may
476
+ // long since have gone. It used to be written onto whichever session
477
+ // was still there, and dropped outright when none was.
478
+ this.#host.keyframeTables.learn({ sourceKey, fileIndex }, { times, format: "packet probe" });
479
+ const elapsedMs = Date.now() - backgroundStartedAt;
480
+ this.#host.logger.info(
481
+ times
482
+ ? `transcode: background keyframe probe found ${times.length} keyframes ` +
483
+ `(${elapsedMs}ms) for "${logName}" — later seeks will snap to them`
484
+ : `transcode: background keyframe probe unavailable (${elapsedMs}ms) for "${logName}" ` +
485
+ `— seeks keep using the raw target (falls back to the circuit breaker on failure)`
486
+ );
487
+ });
488
+ }
489
+ this.#host.logger.info(
490
+ `cold-start "${logName}": media-info=${mediaInfoMs}ms (${mediaInfoSource}) ` +
491
+ `keyframes=${keyframeMs === -1 ? "skipped" : keyframeMs === -2 ? "background" : `${keyframeMs}ms`} ` +
492
+ `create-total=${Date.now() - createEntryMs}ms`
493
+ );
494
+ // Which grid this session is cut on. A copy has no choice: only where the
495
+ // source already has a keyframe. A re-encode normally takes the even grid —
496
+ // it produces every frame and may put keyframes where it likes — unless it
497
+ // is a variant of a keyframe-cut session, in which case it must land on the
498
+ // same times to be interchangeable with it.
499
+ // An audio rendition carries no picture, so it has no keyframes of its own
500
+ // to be cut at: it takes the grid of the video it accompanies, whatever that
501
+ // is. Handed one, it uses it; handed none, the base is on the even grid and
502
+ // so is this. Falling into the COPY branch instead — which is what
503
+ // `transcodeVideo: false` means everywhere else — would put the audio of a
504
+ // re-encoded stream on the source's keyframe times while the player was
505
+ // told the even grid, and the two drift further apart with every segment.
506
+ const useKeyframeGrid = hasDuration &&
507
+ keyframes.readable &&
508
+ (audioOnly ? inheritedGrid != null : (!transcodeVideo || inheritedGrid != null));
509
+ // A rung takes the grid it was handed, rather than working one out again
510
+ // from the same index. The two are not the same table: the one it is handed
511
+ // has been CORRECTED wherever a produced segment showed the index to be
512
+ // wrong, and it is those corrected times the copy actually cuts at. Building
513
+ // it afresh here would put the rung back on the index's fiction and undo the
514
+ // alignment it exists for.
515
+ // The file's own table, made once and shared by every session of it. A
516
+ // quality step is a different OUTPUT and the same cuts — which is exactly
517
+ // the agreement `inheritedGrid` used to arrange by handing a copy to each
518
+ // new session — so it is keyed by the file and the kind of grid, and
519
+ // nothing else.
520
+ const timeline = this.#host.timelines.get(
521
+ Timelines.keyFor(sourceKey, fileIndex, useKeyframeGrid ? "keyframe" : "uniform"),
522
+ () => {
523
+ const cut = hasDuration
524
+ ? computeCutGrid({
525
+ useKeyframeGrid,
526
+ durationSeconds,
527
+ segDur: this.#host.segmentDurationSec,
528
+ keyframeTimes: keyframes.times,
529
+ startTime: sourceStartTime
530
+ })
531
+ : { boundaries: [], sourceTimes: [] };
532
+ const inherited = Array.isArray(inheritedGrid?.boundaries) && inheritedGrid.boundaries.length > 1;
533
+ return new Timeline({
534
+ boundaries: inherited ? [...inheritedGrid.boundaries] : cut.boundaries,
535
+ // The file's own clock for those cuts. An inherited table brings its
536
+ // boundaries and not this, so the seek falls back to searching there.
537
+ sourceTimes: inherited ? null : cut.sourceTimes,
538
+ cutGrid: useKeyframeGrid ? "keyframe" : "uniform"
539
+ });
540
+ }
541
+ );
542
+ // What this session will PUBLISH. A member of a family takes its base's
543
+ // published table verbatim; a session with no base publishes what it cuts
544
+ // at. The two differ exactly by the corrections made since the family's
545
+ // first playlist was written, and that difference is what must never reach
546
+ // the player as two different timelines.
547
+ const publishedGrid = timeline.published.length > 1 ? timeline.published : null;
548
+ const segmentCount = timeline.segmentCount;
549
+
550
+ // THE FORMAT, decided before the output is named, and possibly an output
551
+ // already here instead (`encode/quality/output-format.js`).
552
+ const decided = decideOutputFormat({
553
+ encodesPicture: transcodeVideo && carriesVideo,
554
+ exact: forceExactSize,
555
+ target: this.#targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }),
556
+ source: { width: sourceWidth, height: sourceHeight, megabitsPerSecond: file.decode?.megabitsPerSecond ?? null, decode: file.decode },
557
+ fps: outputFps,
558
+ encoder: this.#host.videoEncoder,
559
+ benchmark: this.#host.softwarePresetBenchmark,
560
+ cost: {
561
+ decodeModel: this.#host.decodeCostModel,
562
+ observedDecodeCostSec: this.#host.encodeCost.decodeCostFor(file.key)?.costSec ?? null,
563
+ requiredSpeed: this.#host.hostLoad.requiredSpeedFor(sourceKey, fileIndex)
564
+ },
565
+ chooseBudget: (params) => this.#host.encodeCost.chooseEncodeBudget(params),
566
+ tonemap: applyTonemap,
567
+ capKbps,
568
+ limitsFor: (frame) => this.#host.limitsFor(frame),
569
+ audioLoad: audioLoadOf(
570
+ viewerAudio !== undefined
571
+ ? viewerAudio
572
+ : { transcode: transcodeAudio === true, bitrateKbps: audioSource.bitrateKbps ?? null },
573
+ AUDIO_TRANSCODE_KBPS
574
+ ),
575
+ specWith: (encode) => new OutputSpec({
576
+ sourceKey,
577
+ segmentFormatId: segmentFormat.id,
578
+ // Where it is ACTUALLY cut: a copy whose container states no keyframes
579
+ // is re-encoded onto the even grid, and is named so.
580
+ grid: new CutGrid({ kind: useKeyframeGrid ? "keyframe" : "uniform", fileIndex }),
581
+ video: carriesVideo ? new VideoOutput({ fileIndex, encode }) : null,
582
+ audio: carriesAudio
583
+ ? new AudioOutput({ fileIndex: audioSource.fileIndex, trackIndex: audioSource.sourceTrackIndex, transcode: transcodeAudio === true })
584
+ : null
585
+ }),
586
+ serving: {
587
+ mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
588
+ linkMbps: viewerLinkMbps,
589
+ keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentStore.addresses()),
590
+ readyAt: (key) => this.#host.segmentStore.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
591
+ observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
592
+ }
593
+ });
594
+ if (decided.unavailable) {
595
+ this.#host.logger.info(
596
+ `transcode "${logName}": no output suits this viewer — ${decided.unavailable.reason} ` +
597
+ `${JSON.stringify(decided.unavailable.figures)} (wanted ${decided.wantedKey})`
598
+ );
599
+ const error = new Error(`No output suits this viewer: ${decided.unavailable.reason}.`);
600
+ // Bound by the MACHINE rather than by the viewer's link, for the output a
601
+ // viewer is opening: another proxy is the answer, found before anything
602
+ // plays. A step asked for on their behalf stays "unavailable", which is
603
+ // how every caller of a step already reads a refusal.
604
+ error.code = decided.unavailable.bound === "machine" && typeof claim === "function"
605
+ ? OUTPUT_NO_CAPACITY
606
+ : OUTPUT_UNAVAILABLE;
607
+ error.details = { reason: decided.unavailable.reason, figures: decided.unavailable.figures, wantedKey: decided.wantedKey };
608
+ throw error;
609
+ }
610
+ if (decided.answer) {
611
+ this.#host.logger.info(
612
+ `transcode "${logName}": ${decided.answer.verdict} for this viewer ${JSON.stringify(linkFiguresOf(decided.answer))}`
613
+ );
614
+ }
615
+ const spec = decided.spec;
616
+ const budget = decided.budget;
617
+ if (decided.reusedKey) {
618
+ this.#host.logger.info(`transcode "${logName}": served by an output already here, ${decided.reusedKey}, instead of ${decided.wantedKey}`);
619
+ }
620
+ transcodeVideo = carriesVideo ? spec.transcodesVideo : transcodeVideo;
621
+ const width = spec.video?.encode?.width ?? 0;
622
+ const height = spec.video?.encode?.height ?? 0;
623
+ const outputKey = spec.toKey();
624
+ // THE NAME FOLLOWS FROM THE KEY, so there is nothing to look it up in. A
625
+ // second table held key → name, which is a fact that can go out of step
626
+ // with the thing it points at: a session disposed without the table being
627
+ // cleared leaves a name pointing at nothing, and the next viewer of that
628
+ // output is handed it.
629
+ const existingId = spec.toName();
630
+ if (existingId) {
631
+ const existing = this.#host.outputs.get(existingId);
632
+ if (existing) {
633
+ this.#claimOrRefuse(claim, existing, logName);
634
+ return { output: existing, existed: true, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
635
+ }
636
+ }
637
+
638
+ // Only a session actually made is timed: a viewer joining one costs none
639
+ // of what this figure predicts for the next viewer who has to wait.
640
+ this.#host.hostTimings.rememberSessionCreateLatency(Date.now() - createEntryMs);
641
+ const sessionId = spec.toName();
642
+ const output = new Output({
643
+ encodeWidth: width,
644
+ encodeHeight: height,
645
+ outputFps,
646
+ softwarePreset: spec.video?.encode?.preset ?? null,
647
+ applyTonemap: spec.video?.encode?.tonemap === true
648
+ });
649
+
650
+ const session = new EncodedOutput({
651
+ id: sessionId,
652
+ spec,
653
+ file,
654
+ keyframes,
655
+ timeline,
656
+ segmentFormat,
657
+ output,
658
+ useSyntheticPlaylist: hasDuration,
659
+ playlistText: hasDuration ? mediaPlaylistText({ boundaries: publishedGrid, segmentFormat }) : "",
660
+ variantHeight: forceExactSize && height > 0 ? height : undefined
661
+ });
662
+ this.#host.outputs.set(sessionId, session);
663
+ // THE PLACE ON THIS MACHINE, taken in the same synchronous stretch as the
664
+ // registration: priced as registered, and withdrawn whole if refused, so a
665
+ // refused opening leaves nothing behind — no directory, no timing.
666
+ try {
667
+ this.#claimOrRefuse(claim, session, logName);
668
+ } catch (error) {
669
+ this.#host.outputs.delete(sessionId);
670
+ throw error;
671
+ }
672
+
673
+ // Only now, when nothing above can still throw. Everything from the probe
674
+ // to the keyframe index used to run with the directory already made, so a
675
+ // failure between the two left it behind: nothing tracks a directory whose
676
+ // session was never registered, and no sweep looks for one. Proxy
677
+ // 2.9.101-2.9.102 failed here on every single request and the leftovers
678
+ // were the only trace of it on disk.
679
+ // A RETURN, if this output was held before — and its age, which is the one
680
+ // term of the keeping period that nothing measures. Read BEFORE the
681
+ // directory is claimed, since claiming it is what marks it read.
682
+ this.#host.returns.note({ lastReadAt: this.#host.segmentStore.lastReadAt(spec.toKey()), now: Date.now() });
683
+ this.#host.segmentStore.directoryFor(spec.toKey());
684
+ this.#host.segmentStore.useFormat(spec.toKey(), segmentFormat);
685
+ this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
686
+ this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
687
+ this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
688
+ // Decided before the key was built and only recorded here. Whether the audio
689
+ // travels separately decides the ffmpeg arguments, what the master says,
690
+ // whether the rendition route answers at all AND what the session is keyed
691
+ // on, and those four must agree for the whole life of the session — a
692
+ // session whose picture was encoded without audio cannot start muxing it in
693
+ // at the next restart without either playing it twice or refusing the
694
+ // append, and one keyed as carrying no sound must never mux somebody else's
695
+ // language into a picture two viewers share.
696
+ //
697
+ // It must not be asked a second time, because the answer moves: the offered
698
+ // list is recomputed as the host learns what this source costs, and
699
+ // crossing "two rungs" would flip the arrangement under a stream that is
700
+ // playing.
701
+ this.#host.logger.info(
702
+ // Proxy version on the session-start line: a field report always includes
703
+ // one of these, so "is the host actually running the build I published?"
704
+ // is answered by the log itself instead of a round trip to the machine.
705
+ `transcode ${sessionId} start (proxy ${PROXY_VERSION}) "${logName}" ` +
706
+ // Where the browser asked the encoder to begin. A resume that reaches
707
+ // hls.js but not this call makes the player request a segment nobody
708
+ // was told to produce: measured 2026-08-06, the session began at #0
709
+ // while the player asked for #127 and gave up 45.6 s later. Neither
710
+ // side saying what it meant is why that took three attempts to place.
711
+ `start=${Math.round(normalizedStartPosition)}s ` +
712
+ `video=${transcodeVideo ? `${this.#host.videoEncoder.name}${output.softwarePreset ? `/${output.softwarePreset}` : ""}` : "copy"} ` +
713
+ `audio=${transcodeAudio ? "aac" : "copy"} ` +
714
+ // Branch tag for log correlation: A = video re-encode (fixed GOP, grid
715
+ // aligned, ts-offset); B = video copy (cut at source keyframes, copyts).
716
+ `branch=${transcodeVideo ? "A(reencode,fixed-gop)" : "B(copy,copyts)"} ` +
717
+ `seg=${timeline.cutGrid} ` +
718
+ `${sourceWidth && sourceHeight ? `src=${sourceWidth}x${sourceHeight} ` : ""}` +
719
+ // The size produced, and how it was arrived at: exactly as asked, the
720
+ // budget's rung of the viewer's own ladder, or the box asked for where
721
+ // there is no ladder to choose from.
722
+ `${transcodeVideo
723
+ ? `enc=${output.encodeWidth || "src"}x${output.encodeHeight || "src"}@${output.outputFps} ` +
724
+ `size=${forceExactSize ? "exact" : budget ? `budget rung ${budget.rungIndex + 1}/${budget.ladder.length}` : "asked"} `
725
+ : ""}` +
726
+ // HDR source and whether the tone-map chain was applied (vs washed-out
727
+ // fallback when the filters are missing or on a hardware encoder).
728
+ `${transcodeVideo && mediaInfo.isHdr ? `hdr=1 tonemap=${applyTonemap ? "on" : "off"} ` : ""}` +
729
+ `${sourceStartTime ? `start=${sourceStartTime.toFixed(3)} ` : ""}` +
730
+ `duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount} ` +
731
+ // What this session was keyed on, which is what decides whether the next
732
+ // viewer joins it or starts a second encoder beside it. Printed because
733
+ // a fork was undiagnosable without it: on 2026-09-03 two viewers of one
734
+ // copied picture got two sessions with identical descriptions and
735
+ // byte-identical output, both create requests were 265 bytes, and
736
+ // nothing anywhere said what the two had been told apart by.
737
+ `key=${outputKey}`
738
+ );
739
+
740
+ // Where the first encoder goes is the plan's, placed by the same arithmetic
741
+ // as every later one from where the viewers stand; the requester is placed
742
+ // by the operation that asked for this output.
743
+ return { output: session, existed: false, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
744
+ }
745
+ }