@torrent-tv/proxy 2.88.4 → 2.88.5

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 (489) 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 +322 -322
  13. package/CHANGELOG.md +2266 -2259
  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 -0
  19. package/assets/calibration/audio/aac.m4a +0 -0
  20. package/assets/calibration/audio/ac3.ac3 +0 -0
  21. package/assets/calibration/audio/alac.m4a +0 -0
  22. package/assets/calibration/audio/dts.dts +0 -0
  23. package/assets/calibration/audio/eac3.eac3 +0 -0
  24. package/assets/calibration/audio/flac.flac +0 -0
  25. package/assets/calibration/audio/manifest.json +98 -0
  26. package/assets/calibration/audio/mp2.mp2 +0 -0
  27. package/assets/calibration/audio/mp3.mp3 +0 -0
  28. package/assets/calibration/audio/opus.opus +0 -0
  29. package/assets/calibration/audio/pcm.wav +0 -0
  30. package/assets/calibration/audio/truehd.thd +0 -0
  31. package/assets/calibration/audio/vorbis.ogg +0 -0
  32. package/assets/diagnostics/sctpstate.gdb +31 -31
  33. package/bin/cli.js +684 -684
  34. package/bin/thread-pool.js +30 -30
  35. package/biome.json +412 -411
  36. package/docs/browser-proxy-contract.md +155 -152
  37. package/docs/container-architecture.md +218 -218
  38. package/docs/download-architecture.md +261 -261
  39. package/docs/encode-architecture.md +729 -729
  40. package/docs/encode-run-state.md +96 -96
  41. package/docs/logs.md +97 -97
  42. package/docs/playback-start-forecast.md +56 -0
  43. package/docs/socks5-egress-research.md +114 -114
  44. package/docs/storage-architecture.md +267 -267
  45. package/knip.json +14 -14
  46. package/openspec/changes/adaptive-bitrate/design.md +92 -92
  47. package/openspec/changes/adaptive-bitrate/proposal.md +56 -56
  48. package/openspec/changes/adaptive-bitrate/specs/adaptive-bitrate/spec.md +51 -51
  49. package/openspec/changes/adaptive-bitrate/tasks.md +40 -40
  50. package/openspec/changes/binary-distribution/.openspec.yaml +2 -2
  51. package/openspec/changes/binary-distribution/proposal.md +53 -53
  52. package/openspec/changes/chunked-request-bodies/design.md +81 -81
  53. package/openspec/changes/chunked-request-bodies/proposal.md +53 -53
  54. package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -30
  55. package/openspec/changes/chunked-request-bodies/tasks.md +40 -40
  56. package/openspec/changes/cold-start/design.md +98 -98
  57. package/openspec/changes/cold-start/proposal.md +62 -62
  58. package/openspec/changes/cold-start/specs/cold-start/spec.md +47 -47
  59. package/openspec/changes/cold-start/tasks.md +48 -48
  60. package/openspec/changes/disk-cap/.openspec.yaml +2 -2
  61. package/openspec/changes/disk-cap/proposal.md +37 -37
  62. package/openspec/changes/disk-cap/specs/disk-cap/spec.md +25 -25
  63. package/openspec/changes/disk-cap/tasks.md +19 -19
  64. package/openspec/changes/proxy-observability/.openspec.yaml +2 -2
  65. package/openspec/changes/proxy-observability/design.md +38 -38
  66. package/openspec/changes/proxy-observability/proposal.md +49 -49
  67. package/openspec/changes/proxy-observability/specs/observability/spec.md +33 -33
  68. package/openspec/changes/proxy-observability/tasks.md +21 -21
  69. package/openspec/changes/seek-debounce/design.md +118 -118
  70. package/openspec/changes/seek-debounce/proposal.md +59 -59
  71. package/openspec/changes/seek-debounce/specs/seek-debounce/spec.md +41 -41
  72. package/openspec/changes/seek-debounce/tasks.md +33 -33
  73. package/openspec/changes/subtitle-language/.openspec.yaml +2 -2
  74. package/openspec/changes/subtitle-language/proposal.md +50 -50
  75. package/openspec/changes/subtitle-language/specs/subtitle-language/spec.md +34 -34
  76. package/openspec/changes/subtitle-language/tasks.md +26 -26
  77. package/openspec/changes/track-selection/.openspec.yaml +2 -2
  78. package/openspec/changes/track-selection/design.md +47 -47
  79. package/openspec/changes/track-selection/proposal.md +45 -45
  80. package/openspec/changes/track-selection/specs/track-selection/spec.md +41 -41
  81. package/openspec/changes/track-selection/tasks.md +20 -20
  82. package/openspec/changes/transcode-quality/.openspec.yaml +2 -2
  83. package/openspec/changes/transcode-quality/proposal.md +51 -51
  84. package/openspec/changes/transcode-quality/specs/transcode-quality/spec.md +139 -139
  85. package/openspec/changes/transcode-quality/tasks.md +63 -63
  86. package/openspec/config.yaml +38 -38
  87. package/package.json +1 -1
  88. package/public/.well-known/appspecific/com.chrome.devtools.json +1 -1
  89. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  90. package/research/double-spawn-2026-09-10.md +171 -171
  91. package/research/handover-2026-09-13.md +209 -209
  92. package/research/handover-reader-claims-removal-2026-09-12.md +166 -166
  93. package/research/piece-withdrawn-but-still-claimed-2026-09-12.md +175 -175
  94. package/research/preset-benchmark-size-scaling-2026-08-22.md +55 -55
  95. package/research/priority-map-is-the-truth-2026-09-12.md +225 -225
  96. package/routes/api/client-logs/post.js +86 -86
  97. package/routes/api/delivery-sink/get.js +72 -72
  98. package/routes/api/link-probe/get.js +51 -51
  99. package/routes/api/playback-plan/audio-tracks/post.js +29 -29
  100. package/routes/api/playback-plan/post.js +53 -53
  101. package/routes/api/sources/post.js +36 -36
  102. package/routes/api/sources/stats/get.js +132 -132
  103. package/routes/api/sources/warm/post.js +217 -217
  104. package/routes/api/subtitles/get.js +230 -230
  105. package/routes/api/transcode-sessions/fragment-far/post.js +60 -60
  106. package/routes/api/transcode-sessions/net-report/post.js +138 -138
  107. package/routes/api/transcode-sessions/post.js +178 -178
  108. package/routes/api/transcode-sessions/progress/get.js +27 -27
  109. package/routes/api/transcode-sessions/release/post.js +41 -41
  110. package/routes/api/transcode-sessions/seek/post.js +63 -63
  111. package/routes/health/get.js +13 -13
  112. package/routes/healthz/get.js +13 -13
  113. package/routes/stream/get.js +380 -380
  114. package/routes/transcode/audio-file/get.js +64 -64
  115. package/routes/transcode/audio-warm/get.js +95 -95
  116. package/routes/transcode/session-file/get.js +52 -52
  117. package/routes/transcode/variant-file/get.js +95 -95
  118. package/routes/transcode/variant-warm/get.js +84 -84
  119. package/scripts/build-audio-samples.mjs +31 -0
  120. package/scripts/render-run-graph.js +173 -173
  121. package/server.js +730 -725
  122. package/services/encode/CoverageMap.js +428 -428
  123. package/services/encode/CushionReport.js +345 -345
  124. package/services/encode/EncodeAdmission.js +376 -376
  125. package/services/encode/EncodeOrchestrator.js +1217 -1217
  126. package/services/encode/EncodePlan.js +1366 -1366
  127. package/services/encode/EncodeRun.js +813 -813
  128. package/services/encode/EncodeRuns.js +1237 -1235
  129. package/services/encode/Encoder.js +142 -142
  130. package/services/encode/EncoderSelection.js +38 -38
  131. package/services/encode/LocalObservations.js +359 -359
  132. package/services/encode/NvencEncoder.js +50 -50
  133. package/services/encode/OutputOpening.js +783 -783
  134. package/services/encode/OutputTimes.js +579 -579
  135. package/services/encode/QsvEncoder.js +58 -58
  136. package/services/encode/Renditions.js +2282 -2282
  137. package/services/encode/RunProgress.js +84 -84
  138. package/services/encode/SegmentDemand.js +95 -95
  139. package/services/encode/SoftwareEncoder.js +121 -121
  140. package/services/encode/V4l2m2mEncoder.js +53 -53
  141. package/services/encode/VaapiEncoder.js +66 -66
  142. package/services/encode/args.js +418 -418
  143. package/services/encode/audio-calibration.js +67 -0
  144. package/services/encode/audio-work-rate.js +15 -0
  145. package/services/encode/available-share.js +89 -89
  146. package/services/encode/calibration.js +361 -361
  147. package/services/encode/contention.js +128 -128
  148. package/services/encode/decode-cost-fit.js +363 -363
  149. package/services/encode/encode-exit.js +114 -114
  150. package/services/encode/encode-run-state.js +551 -551
  151. package/services/encode/encoder-readings.js +45 -45
  152. package/services/encode/fingerprint.js +322 -322
  153. package/services/encode/host-load.js +174 -174
  154. package/services/encode/hwaccel.js +1894 -1894
  155. package/services/encode/index.js +9 -9
  156. package/services/encode/learned-median.js +90 -90
  157. package/services/encode/output/EncodedOutput.js +57 -57
  158. package/services/encode/output/Output.js +131 -131
  159. package/services/encode/output/OutputCatalog.js +414 -414
  160. package/services/encode/output/OutputSpec.js +390 -390
  161. package/services/encode/output/Timeline.js +308 -308
  162. package/services/encode/output/cut-grid.js +107 -107
  163. package/services/encode/output/index.js +20 -20
  164. package/services/encode/output/ladder.js +32 -32
  165. package/services/encode/output/playlists.js +284 -284
  166. package/services/encode/output/rates.js +125 -125
  167. package/services/encode/output-key-format.js +21 -21
  168. package/services/encode/quality/EncodeCost.js +1167 -1150
  169. package/services/encode/quality/HostLoad.js +525 -525
  170. package/services/encode/quality/HostTimings.js +249 -249
  171. package/services/encode/quality/OutputQualityState.js +28 -28
  172. package/services/encode/quality/QualityController.js +935 -935
  173. package/services/encode/quality/QualityOffer.js +416 -416
  174. package/services/encode/quality/drain-threat.js +47 -47
  175. package/services/encode/quality/link-budget.js +349 -349
  176. package/services/encode/quality/output-format.js +319 -319
  177. package/services/encode/quality/serving-output.js +216 -216
  178. package/services/encode/quality/visible-rung.js +57 -57
  179. package/services/encode/run-budget.js +97 -97
  180. package/services/encode/run-command.js +754 -754
  181. package/services/encode/run-costs.js +155 -155
  182. package/services/encode/run-inputs.js +42 -42
  183. package/services/encode/segment-formats/fmp4.js +458 -456
  184. package/services/encode/segment-formats/index.js +85 -85
  185. package/services/encode/segment-formats/init-compat.js +324 -324
  186. package/services/encode/segment-formats/mp4-boxes.js +12 -1
  187. package/services/encode/segment-formats/mpegts.js +134 -134
  188. package/services/encode/start-stop-cost.js +178 -178
  189. package/services/encode/throughput.js +97 -97
  190. package/services/encode/torrent-cost.js +88 -88
  191. package/services/identity/installation-id.js +38 -38
  192. package/services/media/ContainerOrchestrator.js +149 -149
  193. package/services/media/KeyframeTables.js +316 -316
  194. package/services/media/SourceFile.js +298 -298
  195. package/services/media/SubtitleCues.js +520 -520
  196. package/services/media/SubtitleOrchestrator.js +167 -167
  197. package/services/media/audio-inventory.js +299 -298
  198. package/services/media/container/AviContainer.js +266 -266
  199. package/services/media/container/Container.js +609 -609
  200. package/services/media/container/ContainerFactory.js +56 -56
  201. package/services/media/container/KeyframeTable.js +272 -272
  202. package/services/media/container/MatroskaContainer.js +1494 -1494
  203. package/services/media/container/Mp4Container.js +1344 -1344
  204. package/services/media/container/ebml-reader.js +159 -159
  205. package/services/media/ffmpeg-banner.js +260 -260
  206. package/services/media/keyframe-probe.js +157 -157
  207. package/services/media/media-info-probe.js +93 -93
  208. package/services/media/playback-planner.js +931 -931
  209. package/services/media/tracks/AudioTrack.js +143 -143
  210. package/services/media/tracks/ContainerTrack.js +75 -75
  211. package/services/media/tracks/ImageSubtitleTrack.js +19 -19
  212. package/services/media/tracks/SubtitleTrack.js +38 -38
  213. package/services/media/tracks/TextSubtitleTrack.js +287 -287
  214. package/services/media/tracks/VideoTrack.js +33 -33
  215. package/services/media/tracks/audio-bound.js +233 -233
  216. package/services/media/tracks/index.js +15 -15
  217. package/services/media/tracks/language-detect.js +174 -174
  218. package/services/server/OutputLifecycle.js +418 -418
  219. package/services/server/SegmentServing.js +1150 -1150
  220. package/services/server/ViewerRequests.js +785 -760
  221. package/services/server/WaitLedger.js +142 -142
  222. package/services/server/controllers/PlaybackController.js +40 -40
  223. package/services/server/controllers/SubtitleController.js +109 -109
  224. package/services/server/http-responses.js +60 -60
  225. package/services/server/playback-readiness.js +516 -708
  226. package/services/server/transcode-session-files.js +325 -325
  227. package/services/server/wire-outputs.js +1020 -995
  228. package/services/storage/Diagnostics.js +202 -202
  229. package/services/storage/MachineBudget.js +235 -235
  230. package/services/storage/allowance.js +107 -107
  231. package/services/storage/core-dumps.js +106 -106
  232. package/services/storage/files/CompletedFiles.js +391 -391
  233. package/services/storage/files/piece-from-whole-file.js +118 -118
  234. package/services/storage/free.js +71 -71
  235. package/services/storage/keep.js +48 -48
  236. package/services/storage/machine-memory.js +56 -56
  237. package/services/storage/memory-report.js +575 -575
  238. package/services/storage/piece-store/piece-disk-store.js +539 -539
  239. package/services/storage/piece-store/piece-lru.js +495 -495
  240. package/services/storage/piece-store/shared-piece-store.js +1937 -1931
  241. package/services/storage/returns.js +103 -103
  242. package/services/storage/segment-store/SegmentStore.js +1255 -1240
  243. package/services/storage/wire.js +175 -175
  244. package/services/torrent/demand/DemandRegister.js +202 -202
  245. package/services/torrent/demand/Urgency.js +137 -137
  246. package/services/torrent/demand/Window.js +118 -118
  247. package/services/torrent/demand/index.js +8 -8
  248. package/services/torrent/demand/pieces.js +140 -140
  249. package/services/torrent/download/SwarmSelection.js +386 -386
  250. package/services/torrent/download/registry.js +102 -102
  251. package/services/torrent/download/withdraw-claim.js +80 -80
  252. package/services/torrent/files.js +455 -455
  253. package/services/torrent/naming.js +619 -619
  254. package/services/torrent/piece-store-of.js +29 -29
  255. package/services/torrent/supply-margin.js +262 -262
  256. package/services/torrent/torrent-pool.js +2688 -2675
  257. package/services/torrent/worker/background-fill.js +213 -213
  258. package/services/torrent/worker/channel.js +271 -271
  259. package/services/torrent/worker/client.js +765 -765
  260. package/services/torrent/worker/fastest-wires.js +342 -342
  261. package/services/torrent/worker/handle-state.js +23 -23
  262. package/services/torrent/worker/held-bytes.js +155 -155
  263. package/services/torrent/worker/install-webrtc-shim.js +32 -32
  264. package/services/torrent/worker/piece-reader.js +1078 -1078
  265. package/services/torrent/worker/pool-adapter.js +371 -371
  266. package/services/torrent/worker/protocol.js +184 -184
  267. package/services/torrent/worker/resume-warm.js +107 -107
  268. package/services/torrent/worker/webrtc-shim.js +219 -219
  269. package/services/torrent/worker/worker.js +1129 -1129
  270. package/services/transport/data-channel-handler.js +1369 -1369
  271. package/services/transport/delivery-probe.js +842 -842
  272. package/services/transport/health-collector.js +53 -53
  273. package/services/transport/nat-classifier.js +231 -231
  274. package/services/transport/packet-witness.js +808 -808
  275. package/services/transport/port-mapper.js +235 -235
  276. package/services/transport/registry-api.js +81 -81
  277. package/services/transport/tunnel-client.js +447 -447
  278. package/services/transport/usrsctp-state.js +175 -175
  279. package/services/transport/webrtc-manager.js +484 -484
  280. package/services/viewer/Assignments.js +340 -340
  281. package/services/viewer/PriorityMap.js +390 -390
  282. package/services/viewer/PriorityOrchestrator.js +325 -325
  283. package/services/viewer/Viewer.js +691 -691
  284. package/services/viewer/Viewers.js +368 -368
  285. package/services/viewer/active-output.js +37 -37
  286. package/services/viewer/audio-start.js +46 -46
  287. package/services/viewer/buffer-trend.js +81 -81
  288. package/services/viewer/choices.js +647 -647
  289. package/services/viewer/positions.js +126 -126
  290. package/services/viewer/report-intake.js +46 -46
  291. package/store/source-registry.js +71 -71
  292. package/test/asset-paths.test.js +28 -28
  293. package/test/audio-calibration.test.js +23 -0
  294. package/test/audio-inventory.test.js +212 -212
  295. package/test/audio-track-bitrate.test.js +40 -40
  296. package/test/auto-quality-step.test.js +707 -707
  297. package/test/available-share.test.js +76 -76
  298. package/test/background-fill.test.js +190 -190
  299. package/test/client-log-file.test.js +110 -110
  300. package/test/completed-files.test.js +115 -115
  301. package/test/concurrent-cost.test.js +148 -148
  302. package/test/container-media-info.test.js +228 -228
  303. package/test/contention.test.js +76 -76
  304. package/test/core-dumps.test.js +57 -57
  305. package/test/coverage-follows-the-disk.test.js +228 -228
  306. package/test/coverage-map.test.js +195 -195
  307. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  308. package/test/cut-times-timeline.test.js +65 -65
  309. package/test/cuts-follow-published-grid.test.js +109 -109
  310. package/test/data-channel-frame.test.js +63 -63
  311. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  312. package/test/dead-torrent-handle.test.js +52 -52
  313. package/test/declared-rates.test.js +116 -116
  314. package/test/declared-tracks.test.js +43 -43
  315. package/test/decode-cost-fit.test.js +202 -202
  316. package/test/decode-cost.test.js +462 -462
  317. package/test/delivery-probe.test.js +393 -393
  318. package/test/demand-register.test.js +206 -206
  319. package/test/dht-bootstrap.test.js +72 -72
  320. package/test/drain-threat.test.js +65 -65
  321. package/test/duplicate-add.test.js +48 -48
  322. package/test/encode-admission.test.js +146 -146
  323. package/test/encode-cost.test.js +283 -283
  324. package/test/encode-exit.test.js +111 -111
  325. package/test/encode-orchestrator.test.js +419 -419
  326. package/test/encode-plan-viewers.test.js +718 -718
  327. package/test/encode-plan.test.js +545 -545
  328. package/test/encode-run-state.test.js +314 -314
  329. package/test/encode-run.test.js +162 -162
  330. package/test/encode-slope.test.js +46 -46
  331. package/test/encoded-output.test.js +39 -39
  332. package/test/encoder-kinds.test.js +122 -122
  333. package/test/encoder-readings.test.js +46 -46
  334. package/test/every-claimant-is-told-its-share.test.js +152 -152
  335. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  336. package/test/failed-start-breaker.test.js +202 -202
  337. package/test/fastest-wires.test.js +143 -143
  338. package/test/ffmpeg-stream-counts.test.js +78 -78
  339. package/test/file-edges.test.js +191 -191
  340. package/test/fmp4-presentation-clock.test.js +162 -147
  341. package/test/fmp4-self-contained.test.js +80 -80
  342. package/test/fmp4-timestamps.test.js +140 -140
  343. package/test/fmp4-track-completeness.test.js +41 -41
  344. package/test/format-keyed-outputs.test.js +78 -78
  345. package/test/health-metrics.test.js +38 -38
  346. package/test/held-request-width.test.js +157 -157
  347. package/test/helpers/encode-run.js +136 -136
  348. package/test/helpers/held-file.js +29 -29
  349. package/test/helpers/manager.js +57 -57
  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 +102 -102
  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 +112 -112
  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 +292 -292
  370. package/test/matroska-cues-track.test.js +192 -192
  371. package/test/memory-budget.test.js +390 -390
  372. package/test/move-cost.test.js +216 -216
  373. package/test/mp4-subtitles.test.js +173 -173
  374. package/test/one-authority.test.js +285 -285
  375. package/test/one-budget.test.js +149 -149
  376. package/test/one-output-one-session.test.js +273 -270
  377. package/test/one-resource-divided.test.js +185 -185
  378. package/test/one-serving-output-per-height.test.js +458 -458
  379. package/test/orchestrator-wired.test.js +206 -206
  380. package/test/output-catalog.test.js +39 -39
  381. package/test/output-shape.test.js +21 -21
  382. package/test/output-spec.test.js +251 -251
  383. package/test/output-speed.test.js +88 -88
  384. package/test/outputs-being-prepared.test.js +40 -40
  385. package/test/packet-witness-ring.test.js +236 -236
  386. package/test/packet-witness.test.js +148 -148
  387. package/test/piece-disk-store.test.js +401 -401
  388. package/test/piece-from-whole-file.test.js +129 -129
  389. package/test/piece-lru.test.js +319 -319
  390. package/test/piece-reader.test.js +162 -162
  391. package/test/piece-selection-offset.test.js +85 -85
  392. package/test/piece-store-eviction.test.js +595 -595
  393. package/test/piece-store-never-refuses.test.js +153 -153
  394. package/test/piece-store-reservations.test.js +403 -403
  395. package/test/piece-store-slow-disk.test.js +159 -159
  396. package/test/piece-tail.test.js +97 -97
  397. package/test/plan-host-timings.test.js +68 -68
  398. package/test/plan-is-steady.test.js +225 -225
  399. package/test/playback-readiness.test.js +483 -453
  400. package/test/playback-start-regressions.test.js +99 -99
  401. package/test/priority-map-download.test.js +174 -174
  402. package/test/priority-map-emptied.test.js +204 -204
  403. package/test/priority-map-per-output.test.js +215 -215
  404. package/test/priority-map.test.js +163 -163
  405. package/test/probe-wedge-certainty.test.js +60 -60
  406. package/test/produced-copy-choice.test.js +213 -213
  407. package/test/published-timeline.test.js +83 -83
  408. package/test/quality-offer.test.js +162 -162
  409. package/test/quality-variants.test.js +1257 -1257
  410. package/test/rate-control-in-the-output.test.js +180 -180
  411. package/test/read-survives-withdrawal.test.js +164 -164
  412. package/test/read-window.test.js +365 -365
  413. package/test/resume-warm.test.js +39 -39
  414. package/test/run-graph-drift.test.js +37 -37
  415. package/test/run-inputs.test.js +80 -80
  416. package/test/run-intervals.test.js +100 -100
  417. package/test/run-position-follows-published-grid.test.js +89 -89
  418. package/test/run-progress.test.js +65 -65
  419. package/test/same-height-switch.test.js +664 -664
  420. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  421. package/test/seek-landing.test.js +109 -109
  422. package/test/seek-target-not-superseded.test.js +195 -195
  423. package/test/segment-closed-on-both-branches.test.js +96 -96
  424. package/test/segment-cut-times.test.js +63 -63
  425. package/test/segment-demand.test.js +80 -80
  426. package/test/segment-hold-supersede.test.js +91 -91
  427. package/test/segment-judged-by-its-own-header.test.js +221 -221
  428. package/test/segment-serve-wiring.test.js +475 -475
  429. package/test/segment-store-eviction.test.js +247 -247
  430. package/test/segment-store.test.js +338 -323
  431. package/test/segment-true-start.test.js +86 -86
  432. package/test/segments-are-shared.test.js +176 -176
  433. package/test/send-chunk-bytes.test.js +86 -86
  434. package/test/serving-existing-output.test.js +105 -105
  435. package/test/serving-output.test.js +102 -102
  436. package/test/shared-piece-store.test.js +310 -310
  437. package/test/sidecar-naming.test.js +142 -142
  438. package/test/soundtrack-rate-bound.test.js +289 -289
  439. package/test/source-file.test.js +133 -133
  440. package/test/source-registry.test.js +18 -18
  441. package/test/split-a-stretch.test.js +139 -139
  442. package/test/stale-request-after-seek.test.js +158 -158
  443. package/test/startup-readings.test.js +124 -124
  444. package/test/stream-route.test.js +209 -209
  445. package/test/subtitle-cue-framing.test.js +200 -200
  446. package/test/subtitle-cue-source.test.js +102 -102
  447. package/test/subtitle-cue-walk.test.js +370 -370
  448. package/test/subtitle-cursor.test.js +63 -63
  449. package/test/subtitle-defaults.test.js +118 -118
  450. package/test/subtitle-language.test.js +252 -252
  451. package/test/subtitle-track-numbering.test.js +386 -386
  452. package/test/supply-margin.test.js +177 -177
  453. package/test/swarm-follows-readers.test.js +174 -174
  454. package/test/swarm-reach.test.js +130 -130
  455. package/test/swarm-selection.test.js +220 -220
  456. package/test/tail-duplication.test.js +167 -167
  457. package/test/the-channel-has-both-ends.test.js +91 -91
  458. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  459. package/test/thread-pool.test.js +53 -53
  460. package/test/timeline.test.js +84 -84
  461. package/test/torrent-contents.test.js +235 -235
  462. package/test/torrent-cost.test.js +71 -71
  463. package/test/torrent-files.test.js +221 -221
  464. package/test/torrent-naming.test.js +255 -255
  465. package/test/tracks-begin-together.test.js +209 -209
  466. package/test/tunnel-renewal.test.js +167 -167
  467. package/test/two-viewers-one-picture.test.js +504 -504
  468. package/test/upload-hurry.test.js +186 -186
  469. package/test/usrsctp-state.test.js +131 -131
  470. package/test/video-facts.test.js +102 -102
  471. package/test/viewer-assignments.test.js +143 -143
  472. package/test/viewer-outputs.test.js +285 -285
  473. package/test/viewer-presence.test.js +116 -116
  474. package/test/viewer-requests-admission.test.js +89 -89
  475. package/test/viewer-states.test.js +189 -189
  476. package/test/viewer-subtitle-subscription.test.js +96 -96
  477. package/test/viewer.test.js +139 -139
  478. package/test/viewing-generations.test.js +390 -390
  479. package/test/visible-rung.test.js +37 -37
  480. package/test/wait-ledger.test.js +100 -100
  481. package/test/webrtc-shim.test.js +149 -149
  482. package/test/wedge-certainty.test.js +131 -131
  483. package/test/withdraw-piece-claim.test.js +212 -212
  484. package/test/worker-channel.test.js +158 -158
  485. package/utils/client-log-file.js +151 -151
  486. package/utils/logger.js +312 -312
  487. package/utils/parse-range.js +25 -25
  488. package/utils/perf.js +59 -59
  489. package/utils/torrent-source-key.js +38 -38
@@ -1,783 +1,783 @@
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 the table is
453
- // still unanswered — which is not the same as a file with no keyframes,
454
- // and the distinction is the table's own (`answered` against
455
- // `readable`). Recorded as an absence it would make a passing shortage
456
- // of bytes look like a property of the bytes, and every later session
457
- // of the file would re-encode a picture that can be copied.
458
- this.#host.logger.warn(
459
- `transcode: the keyframe table for "${logName}" has not arrived in ` +
460
- `${Math.round(this.#host.keyframeTables.budgetMs / 1000)}s, so this session re-encodes the picture ` +
461
- "instead of copying it; the read goes on and the next session of this file gets the copy"
462
- );
463
- }
464
- if (!keyframes.readable) {
465
- // No index, so there is no honest grid for a COPY: a copied picture can
466
- // only be cut at the source's own keyframes, and we do not know where
467
- // they are. Declaring an even grid instead is a falsehood the player
468
- // punishes — it walks the whole file to rebuild the timeline, or shows
469
- // audio with no picture because a segment begins with nothing
470
- // decodable (both field-observed 2026-08-02).
471
- //
472
- // Re-encoding is the honest answer and costs an encoder: keyframes are
473
- // then PLACED at our own cut times rather than found, so the grid is
474
- // correct by construction whatever the container. MPEG-TS is the case
475
- // this exists for — measured 2026-08-21, 669 real keyframes and no
476
- // index of any kind to read them from — and a container whose index
477
- // could not be read in the budget lands here too, which is right for
478
- // the same reason.
479
- transcodeVideo = true;
480
- if (keyframes.answered) {
481
- this.#host.logger.warn(
482
- `transcode: no keyframe index in the ${keyframes.format} container for ` +
483
- `"${logName}" — a copied picture has no honest grid without one, so the video is ` +
484
- "re-encoded instead and its keyframes are placed on our own cuts"
485
- );
486
- }
487
- }
488
- } else if (hasDuration && transcodeVideo) {
489
- // Re-encode path: keyframeTimes are ONLY used to snap a LATER seek (see
490
- // #startEncodeRun) — segment boundaries stay on the uniform grid either
491
- // way. So this does NOT need to block session creation / the first
492
- // segment's start. Run it in the background with a FULL budget instead of
493
- // the 6 s cap: AVI-class containers need a full packet scan, which 6 s can
494
- // never afford without delaying playback start — that starved budget is
495
- // exactly why the probe kept missing on the container where the seek bug
496
- // was field-diagnosed. A run reads the file's table on every call, so a
497
- // seek that happens AFTER this finishes picks it up automatically; one
498
- // that happens before falls back to the existing circuit breaker as a
499
- // safety net (no regression either way).
500
- keyframeMs = -2;
501
- const backgroundStartedAt = Date.now();
502
- void this.#host.probeKeyframeTimes(inputFile.streamUrl(this.#host.localBaseUrl).toString(), 25_000).then((times) => {
503
- // Into the FILE's table, which the picture, its quality steps and a
504
- // second viewer's session all hold — so nothing has to be alive for the
505
- // answer to be kept, and the session this probe was started for may
506
- // long since have gone. It used to be written onto whichever session
507
- // was still there, and dropped outright when none was.
508
- this.#host.keyframeTables.learn({ sourceKey, fileIndex }, { times, format: "packet probe" });
509
- const elapsedMs = Date.now() - backgroundStartedAt;
510
- this.#host.logger.info(
511
- times
512
- ? `transcode: background keyframe probe found ${times.length} keyframes ` +
513
- `(${elapsedMs}ms) for "${logName}" — later seeks will snap to them`
514
- : `transcode: background keyframe probe unavailable (${elapsedMs}ms) for "${logName}" ` +
515
- `— seeks keep using the raw target (falls back to the circuit breaker on failure)`
516
- );
517
- });
518
- }
519
- this.#host.logger.info(
520
- `cold-start "${logName}": media-info=${mediaInfoMs}ms (${mediaInfoSource}) ` +
521
- `keyframes=${keyframeMs === -1 ? "skipped" : keyframeMs === -2 ? "background" : `${keyframeMs}ms`} ` +
522
- `create-total=${Date.now() - createEntryMs}ms`
523
- );
524
- // Which grid this session is cut on. A copy has no choice: only where the
525
- // source already has a keyframe. A re-encode normally takes the even grid —
526
- // it produces every frame and may put keyframes where it likes — unless it
527
- // is a variant of a keyframe-cut session, in which case it must land on the
528
- // same times to be interchangeable with it.
529
- // An audio rendition carries no picture, so it has no keyframes of its own
530
- // to be cut at: it takes the grid of the video it accompanies, whatever that
531
- // is. Handed one, it uses it; handed none, the base is on the even grid and
532
- // so is this. Falling into the COPY branch instead — which is what
533
- // `transcodeVideo: false` means everywhere else — would put the audio of a
534
- // re-encoded stream on the source's keyframe times while the player was
535
- // told the even grid, and the two drift further apart with every segment.
536
- const useKeyframeGrid = hasDuration &&
537
- keyframes.readable &&
538
- (audioOnly ? inheritedGrid != null : (!transcodeVideo || inheritedGrid != null));
539
- // A rung takes the grid it was handed, rather than working one out again
540
- // from the same index. The two are not the same table: the one it is handed
541
- // has been CORRECTED wherever a produced segment showed the index to be
542
- // wrong, and it is those corrected times the copy actually cuts at. Building
543
- // it afresh here would put the rung back on the index's fiction and undo the
544
- // alignment it exists for.
545
- // The file's own table, made once and shared by every session of it. A
546
- // quality step is a different OUTPUT and the same cuts — which is exactly
547
- // the agreement `inheritedGrid` used to arrange by handing a copy to each
548
- // new session — so it is keyed by the file and the kind of grid, and
549
- // nothing else.
550
- const timeline = this.#host.timelines.get(
551
- Timelines.keyFor(sourceKey, fileIndex, useKeyframeGrid ? "keyframe" : "uniform"),
552
- () => {
553
- const cut = hasDuration
554
- ? computeCutGrid({
555
- useKeyframeGrid,
556
- durationSeconds,
557
- segDur: this.#host.segmentDurationSec,
558
- keyframeTimes: keyframes.times,
559
- startTime: sourceStartTime
560
- })
561
- : { boundaries: [], sourceTimes: [] };
562
- const inherited = Array.isArray(inheritedGrid?.boundaries) && inheritedGrid.boundaries.length > 1;
563
- return new Timeline({
564
- boundaries: inherited ? [...inheritedGrid.boundaries] : cut.boundaries,
565
- // The file's own clock for those cuts. An inherited table brings its
566
- // boundaries and not this, so the seek falls back to searching there.
567
- sourceTimes: inherited ? null : cut.sourceTimes,
568
- cutGrid: useKeyframeGrid ? "keyframe" : "uniform"
569
- });
570
- }
571
- );
572
- // What this session will PUBLISH. A member of a family takes its base's
573
- // published table verbatim; a session with no base publishes what it cuts
574
- // at. The two differ exactly by the corrections made since the family's
575
- // first playlist was written, and that difference is what must never reach
576
- // the player as two different timelines.
577
- const publishedGrid = timeline.published.length > 1 ? timeline.published : null;
578
- const segmentCount = timeline.segmentCount;
579
-
580
- // THE FORMAT, decided before the output is named, and possibly an output
581
- // already here instead (`encode/quality/output-format.js`).
582
- const decided = decideOutputFormat({
583
- encodesPicture: transcodeVideo && carriesVideo,
584
- exact: forceExactSize,
585
- target: this.#targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }),
586
- source: { width: sourceWidth, height: sourceHeight, megabitsPerSecond: file.decode?.megabitsPerSecond ?? null, decode: file.decode },
587
- fps: outputFps,
588
- encoder: this.#host.videoEncoder,
589
- benchmark: this.#host.softwarePresetBenchmark,
590
- cost: {
591
- decodeModel: this.#host.decodeCostModel,
592
- observedDecodeCostSec: this.#host.encodeCost.decodeCostFor(file.key)?.costSec ?? null,
593
- requiredSpeed: this.#host.hostLoad.requiredSpeedFor(sourceKey, fileIndex)
594
- },
595
- chooseBudget: (params) => this.#host.encodeCost.chooseEncodeBudget(params),
596
- machineAdmission: this.#host.admission
597
- ? (candidate) => this.#host.admission.previewCandidate(candidate, file)
598
- : null,
599
- tonemap: applyTonemap,
600
- capKbps,
601
- limitsFor: (frame) => this.#host.limitsFor(frame),
602
- audioLoad: viewerAudio !== undefined
603
- ? soundtrackLoadOf(viewerAudio?.entry ?? null, viewerAudio ? viewerAudio.transcode : null)
604
- : soundtrackLoadOf(audioSource.entry, audioTranscoded),
605
- specWith: (encode) => new OutputSpec({
606
- sourceKey,
607
- segmentFormatId: segmentFormat.id,
608
- // Where it is ACTUALLY cut: a copy whose container states no keyframes
609
- // is re-encoded onto the even grid, and is named so.
610
- grid: new CutGrid({ kind: useKeyframeGrid ? "keyframe" : "uniform", fileIndex }),
611
- video: carriesVideo ? new VideoOutput({ fileIndex, encode }) : null,
612
- audio: carriesAudio
613
- ? new AudioOutput({ fileIndex: audioSource.fileIndex, trackIndex: audioSource.sourceTrackIndex, transcode: audioTranscoded })
614
- : null
615
- }),
616
- serving: {
617
- mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
618
- linkMbps: viewerLinkMbps,
619
- keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentOutputFiles.addresses()),
620
- readyAt: (key) => this.#host.segmentOutputFiles.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
621
- observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
622
- }
623
- });
624
- if (decided.unavailable) {
625
- this.#host.logger.info(
626
- `transcode "${logName}": no output suits this viewer — ${decided.unavailable.reason} ` +
627
- `${JSON.stringify(decided.unavailable.figures)} (wanted ${decided.wantedKey})`
628
- );
629
- const error = new Error(`No output suits this viewer: ${decided.unavailable.reason}.`);
630
- // Bound by the MACHINE rather than by the viewer's link, for the output a
631
- // viewer is opening: another proxy is the answer, found before anything
632
- // plays. A step asked for on their behalf stays "unavailable", which is
633
- // how every caller of a step already reads a refusal.
634
- error.code = decided.unavailable.bound === "machine" && typeof claim === "function"
635
- ? OUTPUT_NO_CAPACITY
636
- : OUTPUT_UNAVAILABLE;
637
- error.details = {
638
- reason: decided.unavailable.reason,
639
- // How many soundtracks the viewer could choose instead, so the page can
640
- // offer another one only where there is one to offer.
641
- figures: decided.unavailable.figures
642
- ? { ...decided.unavailable.figures, soundtracks: this.#host.renditions.offeredSoundtrackCount(sourceKey, fileIndex) }
643
- : null,
644
- wantedKey: decided.wantedKey
645
- };
646
- throw error;
647
- }
648
- if (decided.answer) {
649
- this.#host.logger.info(
650
- `transcode "${logName}": ${decided.answer.verdict} for this viewer ${JSON.stringify(linkFiguresOf(decided.answer))}`
651
- );
652
- }
653
- const spec = decided.spec;
654
- const budget = decided.budget;
655
- if (decided.reusedKey) {
656
- this.#host.logger.info(`transcode "${logName}": served by an output already here, ${decided.reusedKey}, instead of ${decided.wantedKey}`);
657
- }
658
- transcodeVideo = carriesVideo ? spec.transcodesVideo : transcodeVideo;
659
- const width = spec.video?.encode?.width ?? 0;
660
- const height = spec.video?.encode?.height ?? 0;
661
- const outputKey = spec.toKey();
662
- // THE NAME FOLLOWS FROM THE KEY, so there is nothing to look it up in. A
663
- // second table held key → name, which is a fact that can go out of step
664
- // with the thing it points at: a session disposed without the table being
665
- // cleared leaves a name pointing at nothing, and the next viewer of that
666
- // output is handed it.
667
- const existingId = spec.toName();
668
- if (existingId) {
669
- const existing = this.#host.outputs.get(existingId);
670
- if (existing) {
671
- this.#claimOrRefuse(claim, existing, logName);
672
- return { output: existing, existed: true, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
673
- }
674
- }
675
-
676
- // Only a session actually made is timed: a viewer joining one costs none
677
- // of what this figure predicts for the next viewer who has to wait.
678
- this.#host.hostTimings.rememberSessionCreateLatency(Date.now() - createEntryMs);
679
- const sessionId = spec.toName();
680
- const output = new Output({
681
- encodeWidth: width,
682
- encodeHeight: height,
683
- outputFps,
684
- softwarePreset: spec.video?.encode?.preset ?? null,
685
- applyTonemap: spec.video?.encode?.tonemap === true
686
- });
687
-
688
- const session = new EncodedOutput({
689
- id: sessionId,
690
- spec,
691
- file,
692
- keyframes,
693
- timeline,
694
- segmentFormat,
695
- output,
696
- useSyntheticPlaylist: hasDuration,
697
- playlistText: hasDuration ? mediaPlaylistText({ boundaries: publishedGrid, segmentFormat }) : "",
698
- variantHeight: forceExactSize && height > 0 ? height : undefined
699
- });
700
- this.#host.outputs.set(sessionId, session);
701
- // THE PLACE ON THIS MACHINE, taken in the same synchronous stretch as the
702
- // registration: priced as registered, and withdrawn whole if refused, so a
703
- // refused opening leaves nothing behind — no directory, no timing.
704
- try {
705
- this.#claimOrRefuse(claim, session, logName);
706
- } catch (error) {
707
- this.#host.outputs.delete(sessionId);
708
- throw error;
709
- }
710
-
711
- // Only now, when nothing above can still throw. Everything from the probe
712
- // to the keyframe index used to run with the directory already made, so a
713
- // failure between the two left it behind: nothing tracks a directory whose
714
- // session was never registered, and no sweep looks for one. Proxy
715
- // 2.9.101-2.9.102 failed here on every single request and the leftovers
716
- // were the only trace of it on disk.
717
- // A RETURN, if this output was held before — and its age, which is the one
718
- // term of the keeping period that nothing measures. Read BEFORE the
719
- // directory is claimed, since claiming it is what marks it read.
720
- this.#host.returns.note({ lastReadAt: this.#host.segmentOutputFiles.lastReadAt(spec.toKey()), now: Date.now() });
721
- this.#host.segmentOutputFiles.directoryFor(spec.toKey());
722
- this.#host.segmentOutputFiles.useFormat(spec.toKey(), segmentFormat);
723
- this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
724
- this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
725
- this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
726
- // Decided before the key was built and only recorded here. Whether the audio
727
- // travels separately decides the ffmpeg arguments, what the master says,
728
- // whether the rendition route answers at all AND what the session is keyed
729
- // on, and those four must agree for the whole life of the session — a
730
- // session whose picture was encoded without audio cannot start muxing it in
731
- // at the next restart without either playing it twice or refusing the
732
- // append, and one keyed as carrying no sound must never mux somebody else's
733
- // language into a picture two viewers share.
734
- //
735
- // It must not be asked a second time, because the answer moves: the offered
736
- // list is recomputed as the host learns what this source costs, and
737
- // crossing "two rungs" would flip the arrangement under a stream that is
738
- // playing.
739
- this.#host.logger.info(
740
- // Proxy version on the session-start line: a field report always includes
741
- // one of these, so "is the host actually running the build I published?"
742
- // is answered by the log itself instead of a round trip to the machine.
743
- `transcode ${sessionId} start (proxy ${PROXY_VERSION}) "${logName}" ` +
744
- // Where the browser asked the encoder to begin. A resume that reaches
745
- // hls.js but not this call makes the player request a segment nobody
746
- // was told to produce: measured 2026-08-06, the session began at #0
747
- // while the player asked for #127 and gave up 45.6 s later. Neither
748
- // side saying what it meant is why that took three attempts to place.
749
- `start=${Math.round(normalizedStartPosition)}s ` +
750
- `video=${transcodeVideo ? `${this.#host.videoEncoder.name}${output.softwarePreset ? `/${output.softwarePreset}` : ""}` : "copy"} ` +
751
- `audio=${audioTranscoded ? "aac" : "copy"} ` +
752
- // Branch tag for log correlation: A = video re-encode (fixed GOP, grid
753
- // aligned, ts-offset); B = video copy (cut at source keyframes, copyts).
754
- `branch=${transcodeVideo ? "A(reencode,fixed-gop)" : "B(copy,copyts)"} ` +
755
- `seg=${timeline.cutGrid} ` +
756
- `${sourceWidth && sourceHeight ? `src=${sourceWidth}x${sourceHeight} ` : ""}` +
757
- // The size produced, and how it was arrived at: exactly as asked, the
758
- // budget's rung of the viewer's own ladder, or the box asked for where
759
- // there is no ladder to choose from.
760
- `${transcodeVideo
761
- ? `enc=${output.encodeWidth || "src"}x${output.encodeHeight || "src"}@${output.outputFps} ` +
762
- `size=${forceExactSize ? "exact" : budget ? `budget rung ${budget.rungIndex + 1}/${budget.ladder.length}` : "asked"} `
763
- : ""}` +
764
- // HDR source and whether the tone-map chain was applied (vs washed-out
765
- // fallback when the filters are missing or on a hardware encoder).
766
- `${transcodeVideo && mediaInfo.isHdr ? `hdr=1 tonemap=${applyTonemap ? "on" : "off"} ` : ""}` +
767
- `${sourceStartTime ? `start=${sourceStartTime.toFixed(3)} ` : ""}` +
768
- `duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount} ` +
769
- // What this session was keyed on, which is what decides whether the next
770
- // viewer joins it or starts a second encoder beside it. Printed because
771
- // a fork was undiagnosable without it: on 2026-09-03 two viewers of one
772
- // copied picture got two sessions with identical descriptions and
773
- // byte-identical output, both create requests were 265 bytes, and
774
- // nothing anywhere said what the two had been told apart by.
775
- `key=${outputKey}`
776
- );
777
-
778
- // Where the first encoder goes is the plan's, placed by the same arithmetic
779
- // as every later one from where the viewers stand; the requester is placed
780
- // by the operation that asked for this output.
781
- return { output: session, existed: false, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
782
- }
783
- }
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 the table is
453
+ // still unanswered — which is not the same as a file with no keyframes,
454
+ // and the distinction is the table's own (`answered` against
455
+ // `readable`). Recorded as an absence it would make a passing shortage
456
+ // of bytes look like a property of the bytes, and every later session
457
+ // of the file would re-encode a picture that can be copied.
458
+ this.#host.logger.warn(
459
+ `transcode: the keyframe table for "${logName}" has not arrived in ` +
460
+ `${Math.round(this.#host.keyframeTables.budgetMs / 1000)}s, so this session re-encodes the picture ` +
461
+ "instead of copying it; the read goes on and the next session of this file gets the copy"
462
+ );
463
+ }
464
+ if (!keyframes.readable) {
465
+ // No index, so there is no honest grid for a COPY: a copied picture can
466
+ // only be cut at the source's own keyframes, and we do not know where
467
+ // they are. Declaring an even grid instead is a falsehood the player
468
+ // punishes — it walks the whole file to rebuild the timeline, or shows
469
+ // audio with no picture because a segment begins with nothing
470
+ // decodable (both field-observed 2026-08-02).
471
+ //
472
+ // Re-encoding is the honest answer and costs an encoder: keyframes are
473
+ // then PLACED at our own cut times rather than found, so the grid is
474
+ // correct by construction whatever the container. MPEG-TS is the case
475
+ // this exists for — measured 2026-08-21, 669 real keyframes and no
476
+ // index of any kind to read them from — and a container whose index
477
+ // could not be read in the budget lands here too, which is right for
478
+ // the same reason.
479
+ transcodeVideo = true;
480
+ if (keyframes.answered) {
481
+ this.#host.logger.warn(
482
+ `transcode: no keyframe index in the ${keyframes.format} container for ` +
483
+ `"${logName}" — a copied picture has no honest grid without one, so the video is ` +
484
+ "re-encoded instead and its keyframes are placed on our own cuts"
485
+ );
486
+ }
487
+ }
488
+ } else if (hasDuration && transcodeVideo) {
489
+ // Re-encode path: keyframeTimes are ONLY used to snap a LATER seek (see
490
+ // #startEncodeRun) — segment boundaries stay on the uniform grid either
491
+ // way. So this does NOT need to block session creation / the first
492
+ // segment's start. Run it in the background with a FULL budget instead of
493
+ // the 6 s cap: AVI-class containers need a full packet scan, which 6 s can
494
+ // never afford without delaying playback start — that starved budget is
495
+ // exactly why the probe kept missing on the container where the seek bug
496
+ // was field-diagnosed. A run reads the file's table on every call, so a
497
+ // seek that happens AFTER this finishes picks it up automatically; one
498
+ // that happens before falls back to the existing circuit breaker as a
499
+ // safety net (no regression either way).
500
+ keyframeMs = -2;
501
+ const backgroundStartedAt = Date.now();
502
+ void this.#host.probeKeyframeTimes(inputFile.streamUrl(this.#host.localBaseUrl).toString(), 25_000).then((times) => {
503
+ // Into the FILE's table, which the picture, its quality steps and a
504
+ // second viewer's session all hold — so nothing has to be alive for the
505
+ // answer to be kept, and the session this probe was started for may
506
+ // long since have gone. It used to be written onto whichever session
507
+ // was still there, and dropped outright when none was.
508
+ this.#host.keyframeTables.learn({ sourceKey, fileIndex }, { times, format: "packet probe" });
509
+ const elapsedMs = Date.now() - backgroundStartedAt;
510
+ this.#host.logger.info(
511
+ times
512
+ ? `transcode: background keyframe probe found ${times.length} keyframes ` +
513
+ `(${elapsedMs}ms) for "${logName}" — later seeks will snap to them`
514
+ : `transcode: background keyframe probe unavailable (${elapsedMs}ms) for "${logName}" ` +
515
+ `— seeks keep using the raw target (falls back to the circuit breaker on failure)`
516
+ );
517
+ });
518
+ }
519
+ this.#host.logger.info(
520
+ `cold-start "${logName}": media-info=${mediaInfoMs}ms (${mediaInfoSource}) ` +
521
+ `keyframes=${keyframeMs === -1 ? "skipped" : keyframeMs === -2 ? "background" : `${keyframeMs}ms`} ` +
522
+ `create-total=${Date.now() - createEntryMs}ms`
523
+ );
524
+ // Which grid this session is cut on. A copy has no choice: only where the
525
+ // source already has a keyframe. A re-encode normally takes the even grid —
526
+ // it produces every frame and may put keyframes where it likes — unless it
527
+ // is a variant of a keyframe-cut session, in which case it must land on the
528
+ // same times to be interchangeable with it.
529
+ // An audio rendition carries no picture, so it has no keyframes of its own
530
+ // to be cut at: it takes the grid of the video it accompanies, whatever that
531
+ // is. Handed one, it uses it; handed none, the base is on the even grid and
532
+ // so is this. Falling into the COPY branch instead — which is what
533
+ // `transcodeVideo: false` means everywhere else — would put the audio of a
534
+ // re-encoded stream on the source's keyframe times while the player was
535
+ // told the even grid, and the two drift further apart with every segment.
536
+ const useKeyframeGrid = hasDuration &&
537
+ keyframes.readable &&
538
+ (audioOnly ? inheritedGrid != null : (!transcodeVideo || inheritedGrid != null));
539
+ // A rung takes the grid it was handed, rather than working one out again
540
+ // from the same index. The two are not the same table: the one it is handed
541
+ // has been CORRECTED wherever a produced segment showed the index to be
542
+ // wrong, and it is those corrected times the copy actually cuts at. Building
543
+ // it afresh here would put the rung back on the index's fiction and undo the
544
+ // alignment it exists for.
545
+ // The file's own table, made once and shared by every session of it. A
546
+ // quality step is a different OUTPUT and the same cuts — which is exactly
547
+ // the agreement `inheritedGrid` used to arrange by handing a copy to each
548
+ // new session — so it is keyed by the file and the kind of grid, and
549
+ // nothing else.
550
+ const timeline = this.#host.timelines.get(
551
+ Timelines.keyFor(sourceKey, fileIndex, useKeyframeGrid ? "keyframe" : "uniform"),
552
+ () => {
553
+ const cut = hasDuration
554
+ ? computeCutGrid({
555
+ useKeyframeGrid,
556
+ durationSeconds,
557
+ segDur: this.#host.segmentDurationSec,
558
+ keyframeTimes: keyframes.times,
559
+ startTime: sourceStartTime
560
+ })
561
+ : { boundaries: [], sourceTimes: [] };
562
+ const inherited = Array.isArray(inheritedGrid?.boundaries) && inheritedGrid.boundaries.length > 1;
563
+ return new Timeline({
564
+ boundaries: inherited ? [...inheritedGrid.boundaries] : cut.boundaries,
565
+ // The file's own clock for those cuts. An inherited table brings its
566
+ // boundaries and not this, so the seek falls back to searching there.
567
+ sourceTimes: inherited ? null : cut.sourceTimes,
568
+ cutGrid: useKeyframeGrid ? "keyframe" : "uniform"
569
+ });
570
+ }
571
+ );
572
+ // What this session will PUBLISH. A member of a family takes its base's
573
+ // published table verbatim; a session with no base publishes what it cuts
574
+ // at. The two differ exactly by the corrections made since the family's
575
+ // first playlist was written, and that difference is what must never reach
576
+ // the player as two different timelines.
577
+ const publishedGrid = timeline.published.length > 1 ? timeline.published : null;
578
+ const segmentCount = timeline.segmentCount;
579
+
580
+ // THE FORMAT, decided before the output is named, and possibly an output
581
+ // already here instead (`encode/quality/output-format.js`).
582
+ const decided = decideOutputFormat({
583
+ encodesPicture: transcodeVideo && carriesVideo,
584
+ exact: forceExactSize,
585
+ target: this.#targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }),
586
+ source: { width: sourceWidth, height: sourceHeight, megabitsPerSecond: file.decode?.megabitsPerSecond ?? null, decode: file.decode },
587
+ fps: outputFps,
588
+ encoder: this.#host.videoEncoder,
589
+ benchmark: this.#host.softwarePresetBenchmark,
590
+ cost: {
591
+ decodeModel: this.#host.decodeCostModel,
592
+ observedDecodeCostSec: this.#host.encodeCost.decodeCostFor(file.key)?.costSec ?? null,
593
+ requiredSpeed: this.#host.hostLoad.requiredSpeedFor(sourceKey, fileIndex)
594
+ },
595
+ chooseBudget: (params) => this.#host.encodeCost.chooseEncodeBudget(params),
596
+ machineAdmission: this.#host.admission
597
+ ? (candidate) => this.#host.admission.previewCandidate(candidate, file)
598
+ : null,
599
+ tonemap: applyTonemap,
600
+ capKbps,
601
+ limitsFor: (frame) => this.#host.limitsFor(frame),
602
+ audioLoad: viewerAudio !== undefined
603
+ ? soundtrackLoadOf(viewerAudio?.entry ?? null, viewerAudio ? viewerAudio.transcode : null)
604
+ : soundtrackLoadOf(audioSource.entry, audioTranscoded),
605
+ specWith: (encode) => new OutputSpec({
606
+ sourceKey,
607
+ segmentFormatId: segmentFormat.id,
608
+ // Where it is ACTUALLY cut: a copy whose container states no keyframes
609
+ // is re-encoded onto the even grid, and is named so.
610
+ grid: new CutGrid({ kind: useKeyframeGrid ? "keyframe" : "uniform", fileIndex }),
611
+ video: carriesVideo ? new VideoOutput({ fileIndex, encode }) : null,
612
+ audio: carriesAudio
613
+ ? new AudioOutput({ fileIndex: audioSource.fileIndex, trackIndex: audioSource.sourceTrackIndex, transcode: audioTranscoded })
614
+ : null
615
+ }),
616
+ serving: {
617
+ mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
618
+ linkMbps: viewerLinkMbps,
619
+ keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentOutputFiles.addresses()),
620
+ readyAt: (key) => this.#host.segmentOutputFiles.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
621
+ observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
622
+ }
623
+ });
624
+ if (decided.unavailable) {
625
+ this.#host.logger.info(
626
+ `transcode "${logName}": no output suits this viewer — ${decided.unavailable.reason} ` +
627
+ `${JSON.stringify(decided.unavailable.figures)} (wanted ${decided.wantedKey})`
628
+ );
629
+ const error = new Error(`No output suits this viewer: ${decided.unavailable.reason}.`);
630
+ // Bound by the MACHINE rather than by the viewer's link, for the output a
631
+ // viewer is opening: another proxy is the answer, found before anything
632
+ // plays. A step asked for on their behalf stays "unavailable", which is
633
+ // how every caller of a step already reads a refusal.
634
+ error.code = decided.unavailable.bound === "machine" && typeof claim === "function"
635
+ ? OUTPUT_NO_CAPACITY
636
+ : OUTPUT_UNAVAILABLE;
637
+ error.details = {
638
+ reason: decided.unavailable.reason,
639
+ // How many soundtracks the viewer could choose instead, so the page can
640
+ // offer another one only where there is one to offer.
641
+ figures: decided.unavailable.figures
642
+ ? { ...decided.unavailable.figures, soundtracks: this.#host.renditions.offeredSoundtrackCount(sourceKey, fileIndex) }
643
+ : null,
644
+ wantedKey: decided.wantedKey
645
+ };
646
+ throw error;
647
+ }
648
+ if (decided.answer) {
649
+ this.#host.logger.info(
650
+ `transcode "${logName}": ${decided.answer.verdict} for this viewer ${JSON.stringify(linkFiguresOf(decided.answer))}`
651
+ );
652
+ }
653
+ const spec = decided.spec;
654
+ const budget = decided.budget;
655
+ if (decided.reusedKey) {
656
+ this.#host.logger.info(`transcode "${logName}": served by an output already here, ${decided.reusedKey}, instead of ${decided.wantedKey}`);
657
+ }
658
+ transcodeVideo = carriesVideo ? spec.transcodesVideo : transcodeVideo;
659
+ const width = spec.video?.encode?.width ?? 0;
660
+ const height = spec.video?.encode?.height ?? 0;
661
+ const outputKey = spec.toKey();
662
+ // THE NAME FOLLOWS FROM THE KEY, so there is nothing to look it up in. A
663
+ // second table held key → name, which is a fact that can go out of step
664
+ // with the thing it points at: a session disposed without the table being
665
+ // cleared leaves a name pointing at nothing, and the next viewer of that
666
+ // output is handed it.
667
+ const existingId = spec.toName();
668
+ if (existingId) {
669
+ const existing = this.#host.outputs.get(existingId);
670
+ if (existing) {
671
+ this.#claimOrRefuse(claim, existing, logName);
672
+ return { output: existing, existed: true, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
673
+ }
674
+ }
675
+
676
+ // Only a session actually made is timed: a viewer joining one costs none
677
+ // of what this figure predicts for the next viewer who has to wait.
678
+ this.#host.hostTimings.rememberSessionCreateLatency(Date.now() - createEntryMs);
679
+ const sessionId = spec.toName();
680
+ const output = new Output({
681
+ encodeWidth: width,
682
+ encodeHeight: height,
683
+ outputFps,
684
+ softwarePreset: spec.video?.encode?.preset ?? null,
685
+ applyTonemap: spec.video?.encode?.tonemap === true
686
+ });
687
+
688
+ const session = new EncodedOutput({
689
+ id: sessionId,
690
+ spec,
691
+ file,
692
+ keyframes,
693
+ timeline,
694
+ segmentFormat,
695
+ output,
696
+ useSyntheticPlaylist: hasDuration,
697
+ playlistText: hasDuration ? mediaPlaylistText({ boundaries: publishedGrid, segmentFormat }) : "",
698
+ variantHeight: forceExactSize && height > 0 ? height : undefined
699
+ });
700
+ this.#host.outputs.set(sessionId, session);
701
+ // THE PLACE ON THIS MACHINE, taken in the same synchronous stretch as the
702
+ // registration: priced as registered, and withdrawn whole if refused, so a
703
+ // refused opening leaves nothing behind — no directory, no timing.
704
+ try {
705
+ this.#claimOrRefuse(claim, session, logName);
706
+ } catch (error) {
707
+ this.#host.outputs.delete(sessionId);
708
+ throw error;
709
+ }
710
+
711
+ // Only now, when nothing above can still throw. Everything from the probe
712
+ // to the keyframe index used to run with the directory already made, so a
713
+ // failure between the two left it behind: nothing tracks a directory whose
714
+ // session was never registered, and no sweep looks for one. Proxy
715
+ // 2.9.101-2.9.102 failed here on every single request and the leftovers
716
+ // were the only trace of it on disk.
717
+ // A RETURN, if this output was held before — and its age, which is the one
718
+ // term of the keeping period that nothing measures. Read BEFORE the
719
+ // directory is claimed, since claiming it is what marks it read.
720
+ this.#host.returns.note({ lastReadAt: this.#host.segmentOutputFiles.lastReadAt(spec.toKey()), now: Date.now() });
721
+ this.#host.segmentOutputFiles.directoryFor(spec.toKey());
722
+ this.#host.segmentOutputFiles.useFormat(spec.toKey(), segmentFormat);
723
+ this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
724
+ this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
725
+ this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
726
+ // Decided before the key was built and only recorded here. Whether the audio
727
+ // travels separately decides the ffmpeg arguments, what the master says,
728
+ // whether the rendition route answers at all AND what the session is keyed
729
+ // on, and those four must agree for the whole life of the session — a
730
+ // session whose picture was encoded without audio cannot start muxing it in
731
+ // at the next restart without either playing it twice or refusing the
732
+ // append, and one keyed as carrying no sound must never mux somebody else's
733
+ // language into a picture two viewers share.
734
+ //
735
+ // It must not be asked a second time, because the answer moves: the offered
736
+ // list is recomputed as the host learns what this source costs, and
737
+ // crossing "two rungs" would flip the arrangement under a stream that is
738
+ // playing.
739
+ this.#host.logger.info(
740
+ // Proxy version on the session-start line: a field report always includes
741
+ // one of these, so "is the host actually running the build I published?"
742
+ // is answered by the log itself instead of a round trip to the machine.
743
+ `transcode ${sessionId} start (proxy ${PROXY_VERSION}) "${logName}" ` +
744
+ // Where the browser asked the encoder to begin. A resume that reaches
745
+ // hls.js but not this call makes the player request a segment nobody
746
+ // was told to produce: measured 2026-08-06, the session began at #0
747
+ // while the player asked for #127 and gave up 45.6 s later. Neither
748
+ // side saying what it meant is why that took three attempts to place.
749
+ `start=${Math.round(normalizedStartPosition)}s ` +
750
+ `video=${transcodeVideo ? `${this.#host.videoEncoder.name}${output.softwarePreset ? `/${output.softwarePreset}` : ""}` : "copy"} ` +
751
+ `audio=${audioTranscoded ? "aac" : "copy"} ` +
752
+ // Branch tag for log correlation: A = video re-encode (fixed GOP, grid
753
+ // aligned, ts-offset); B = video copy (cut at source keyframes, copyts).
754
+ `branch=${transcodeVideo ? "A(reencode,fixed-gop)" : "B(copy,copyts)"} ` +
755
+ `seg=${timeline.cutGrid} ` +
756
+ `${sourceWidth && sourceHeight ? `src=${sourceWidth}x${sourceHeight} ` : ""}` +
757
+ // The size produced, and how it was arrived at: exactly as asked, the
758
+ // budget's rung of the viewer's own ladder, or the box asked for where
759
+ // there is no ladder to choose from.
760
+ `${transcodeVideo
761
+ ? `enc=${output.encodeWidth || "src"}x${output.encodeHeight || "src"}@${output.outputFps} ` +
762
+ `size=${forceExactSize ? "exact" : budget ? `budget rung ${budget.rungIndex + 1}/${budget.ladder.length}` : "asked"} `
763
+ : ""}` +
764
+ // HDR source and whether the tone-map chain was applied (vs washed-out
765
+ // fallback when the filters are missing or on a hardware encoder).
766
+ `${transcodeVideo && mediaInfo.isHdr ? `hdr=1 tonemap=${applyTonemap ? "on" : "off"} ` : ""}` +
767
+ `${sourceStartTime ? `start=${sourceStartTime.toFixed(3)} ` : ""}` +
768
+ `duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount} ` +
769
+ // What this session was keyed on, which is what decides whether the next
770
+ // viewer joins it or starts a second encoder beside it. Printed because
771
+ // a fork was undiagnosable without it: on 2026-09-03 two viewers of one
772
+ // copied picture got two sessions with identical descriptions and
773
+ // byte-identical output, both create requests were 265 bytes, and
774
+ // nothing anywhere said what the two had been told apart by.
775
+ `key=${outputKey}`
776
+ );
777
+
778
+ // Where the first encoder goes is the plan's, placed by the same arithmetic
779
+ // as every later one from where the viewers stand; the requester is placed
780
+ // by the operation that asked for this output.
781
+ return { output: session, existed: false, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
782
+ }
783
+ }