@torrent-tv/proxy 2.89.7 → 2.89.9

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