@torrent-tv/proxy 2.86.0 → 2.87.1

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 (385) hide show
  1. package/CHANGELOG.md +2142 -1915
  2. package/CLAUDE.md +322 -197
  3. package/assets/calibration/NOTICE.md +2 -2
  4. package/bin/cli.js +684 -616
  5. package/biome.json +409 -233
  6. package/docs/browser-proxy-contract.md +94 -0
  7. package/docs/container-architecture.md +218 -213
  8. package/docs/download-architecture.md +7 -7
  9. package/docs/encode-architecture.md +287 -11
  10. package/docs/encode-run-state.md +2 -2
  11. package/docs/logs.md +97 -97
  12. package/docs/{disk-architecture.md → storage-architecture.md} +107 -1
  13. package/openspec/changes/adaptive-bitrate/design.md +2 -2
  14. package/openspec/changes/adaptive-bitrate/proposal.md +1 -1
  15. package/openspec/changes/adaptive-bitrate/tasks.md +1 -1
  16. package/openspec/changes/chunked-request-bodies/design.md +1 -1
  17. package/openspec/changes/chunked-request-bodies/proposal.md +1 -1
  18. package/openspec/changes/chunked-request-bodies/tasks.md +1 -1
  19. package/openspec/changes/cold-start/design.md +1 -1
  20. package/openspec/changes/disk-cap/proposal.md +1 -1
  21. package/openspec/changes/proxy-observability/proposal.md +2 -2
  22. package/openspec/changes/track-selection/proposal.md +1 -1
  23. package/openspec/changes/transcode-quality/proposal.md +1 -1
  24. package/package.json +2 -2
  25. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  26. package/research/double-spawn-2026-09-10.md +171 -171
  27. package/routes/api/playback-plan/post.js +2 -2
  28. package/routes/api/sources/files/get.js +1 -1
  29. package/routes/api/sources/stats/get.js +1 -1
  30. package/routes/api/sources/warm/post.js +10 -3
  31. package/routes/api/subtitles/get.js +230 -230
  32. package/routes/api/transcode-sessions/fragment-far/post.js +3 -3
  33. package/routes/api/transcode-sessions/net-report/post.js +129 -94
  34. package/routes/api/transcode-sessions/post.js +160 -139
  35. package/routes/api/transcode-sessions/progress/get.js +3 -3
  36. package/routes/api/transcode-sessions/release/post.js +3 -3
  37. package/routes/api/transcode-sessions/seek/post.js +12 -3
  38. package/routes/stream/get.js +2 -2
  39. package/routes/transcode/audio-file/get.js +15 -6
  40. package/routes/transcode/audio-warm/get.js +9 -6
  41. package/routes/transcode/session-file/get.js +52 -268
  42. package/routes/transcode/variant-file/get.js +46 -7
  43. package/routes/transcode/variant-warm/get.js +19 -6
  44. package/scripts/render-run-graph.js +1 -1
  45. package/server.js +720 -465
  46. package/services/encode/CoverageMap.js +428 -428
  47. package/services/encode/CushionReport.js +345 -0
  48. package/services/encode/EncodeAdmission.js +332 -0
  49. package/services/{orchestrators → encode}/EncodeOrchestrator.js +307 -29
  50. package/services/encode/EncodeRun.js +16 -9
  51. package/services/encode/EncodeRuns.js +1229 -0
  52. package/services/encode/Encoder.js +18 -2
  53. package/services/encode/EncoderSelection.js +38 -0
  54. package/services/encode/LocalObservations.js +359 -0
  55. package/services/encode/NvencEncoder.js +5 -0
  56. package/services/encode/OutputOpening.js +755 -0
  57. package/services/encode/OutputTimes.js +579 -0
  58. package/services/encode/Renditions.js +2162 -0
  59. package/services/encode/RunProgress.js +84 -0
  60. package/services/encode/SoftwareEncoder.js +12 -7
  61. package/services/encode/args.js +402 -186
  62. package/services/encode/calibration.js +361 -0
  63. package/services/encode/contention.js +128 -128
  64. package/services/encode/encode-run-state.js +16 -20
  65. package/services/encode/fingerprint.js +322 -0
  66. package/services/{hwaccel.js → encode/hwaccel.js} +82 -42
  67. package/services/{learned-median.js → encode/learned-median.js} +11 -0
  68. package/services/encode/output/EncodedOutput.js +57 -0
  69. package/services/encode/output/Output.js +131 -0
  70. package/services/{output/LiveOutputs.js → encode/output/OutputCatalog.js} +141 -40
  71. package/services/encode/output/OutputSpec.js +390 -0
  72. package/services/{output → encode/output}/Timeline.js +12 -37
  73. package/services/encode/output/index.js +20 -0
  74. package/services/encode/output/ladder.js +32 -0
  75. package/services/{output → encode/output}/playlists.js +3 -0
  76. package/services/encode/output-key-format.js +21 -0
  77. package/services/encode/quality/EncodeCost.js +1083 -0
  78. package/services/encode/quality/HostLoad.js +525 -0
  79. package/services/encode/quality/HostTimings.js +249 -0
  80. package/services/encode/quality/OutputQualityState.js +28 -0
  81. package/services/encode/quality/QualityController.js +935 -0
  82. package/services/encode/quality/QualityOffer.js +416 -0
  83. package/services/encode/quality/drain-threat.js +47 -0
  84. package/services/encode/quality/link-budget.js +254 -0
  85. package/services/encode/quality/output-format.js +266 -0
  86. package/services/encode/quality/serving-output.js +216 -0
  87. package/services/encode/quality/visible-rung.js +57 -0
  88. package/services/encode/run-command.js +23 -20
  89. package/services/encode/run-inputs.js +42 -0
  90. package/services/{segment-formats → encode/segment-formats}/fmp4.js +63 -0
  91. package/services/{segment-formats → encode/segment-formats}/index.js +3 -3
  92. package/services/encode/segment-formats/init-compat.js +324 -0
  93. package/services/{segment-formats → encode/segment-formats}/mp4-boxes.js +8 -3
  94. package/services/encode/throughput.js +97 -0
  95. package/services/{orchestrators → media}/ContainerOrchestrator.js +45 -7
  96. package/services/media/KeyframeTables.js +316 -0
  97. package/services/{source → media}/SourceFile.js +7 -55
  98. package/services/{torrent-worker/subtitle-cues.js → media/SubtitleCues.js} +103 -132
  99. package/services/media/SubtitleOrchestrator.js +167 -0
  100. package/services/{audio-inventory.js → media/audio-inventory.js} +7 -1
  101. package/services/{container → media/container}/AviContainer.js +266 -266
  102. package/services/{container → media/container}/Container.js +596 -601
  103. package/services/media/container/ContainerFactory.js +56 -0
  104. package/services/media/container/KeyframeTable.js +272 -0
  105. package/services/{container → media/container}/MatroskaContainer.js +1485 -1485
  106. package/services/{container → media/container}/Mp4Container.js +1244 -1244
  107. package/services/{container → media/container}/SubtitleFileContainer.js +322 -322
  108. package/services/media/keyframe-probe.js +157 -0
  109. package/services/media/media-info-probe.js +93 -0
  110. package/services/{playback-planner.js → media/playback-planner.js} +82 -39
  111. package/services/{tracks → media/tracks}/AudioTrack.js +131 -131
  112. package/services/{tracks → media/tracks}/language-detect.js +174 -174
  113. package/services/server/OutputLifecycle.js +418 -0
  114. package/services/server/SegmentServing.js +1146 -0
  115. package/services/server/ViewerRequests.js +522 -0
  116. package/services/server/controllers/PlaybackController.js +36 -0
  117. package/services/{controllers → server/controllers}/SubtitleController.js +17 -33
  118. package/services/server/http-responses.js +60 -0
  119. package/services/server/transcode-session-files.js +325 -0
  120. package/services/server/wire-outputs.js +983 -0
  121. package/services/storage/Diagnostics.js +202 -0
  122. package/services/storage/MachineBudget.js +235 -0
  123. package/services/{piece-store → storage}/allowance.js +107 -107
  124. package/services/{core-dumps.js → storage/core-dumps.js} +1 -1
  125. package/services/{files → storage/files}/CompletedFiles.js +116 -1
  126. package/services/{disk → storage}/free.js +33 -0
  127. package/services/storage/machine-memory.js +56 -0
  128. package/services/{memory-report.js → storage/memory-report.js} +575 -596
  129. package/services/{piece-store → storage/piece-store}/piece-disk-store.js +0 -7
  130. package/services/{piece-store → storage/piece-store}/shared-piece-store.js +28 -21
  131. package/services/{encode → storage/segment-store}/SegmentStore.js +395 -8
  132. package/services/storage/wire.js +175 -0
  133. package/services/{download → torrent/download}/SwarmSelection.js +2 -2
  134. package/services/{download → torrent/download}/registry.js +2 -2
  135. package/services/torrent/files.js +1 -1
  136. package/services/torrent/piece-store-of.js +29 -0
  137. package/services/{torrent-pool.js → torrent/torrent-pool.js} +26 -119
  138. package/services/{torrent-worker → torrent/worker}/background-fill.js +2 -2
  139. package/services/{torrent-worker → torrent/worker}/channel.js +271 -250
  140. package/services/{torrent-worker → torrent/worker}/client.js +77 -58
  141. package/services/torrent/worker/held-bytes.js +155 -0
  142. package/services/{torrent-worker → torrent/worker}/install-webrtc-shim.js +1 -1
  143. package/services/{torrent-worker → torrent/worker}/piece-reader.js +21 -30
  144. package/services/{torrent-worker → torrent/worker}/pool-adapter.js +101 -137
  145. package/services/{torrent-worker → torrent/worker}/protocol.js +26 -30
  146. package/services/torrent/worker/resume-warm.js +107 -0
  147. package/services/{torrent-worker → torrent/worker}/webrtc-shim.js +2 -2
  148. package/services/{torrent-worker → torrent/worker}/worker.js +68 -159
  149. package/services/{data-channel-handler.js → transport/data-channel-handler.js} +1356 -1356
  150. package/services/{delivery-probe.js → transport/delivery-probe.js} +842 -842
  151. package/services/{health-collector.js → transport/health-collector.js} +6 -35
  152. package/services/{packet-witness.js → transport/packet-witness.js} +808 -784
  153. package/services/{port-mapper.js → transport/port-mapper.js} +1 -1
  154. package/services/{usrsctp-state.js → transport/usrsctp-state.js} +1 -1
  155. package/services/{webrtc-manager.js → transport/webrtc-manager.js} +1 -1
  156. package/services/viewer/Assignments.js +340 -0
  157. package/services/{priority → viewer}/PriorityMap.js +390 -390
  158. package/services/{priority → viewer}/PriorityOrchestrator.js +325 -320
  159. package/services/viewer/Viewer.js +657 -483
  160. package/services/viewer/Viewers.js +368 -257
  161. package/services/viewer/active-output.js +37 -54
  162. package/services/viewer/audio-start.js +4 -3
  163. package/services/viewer/buffer-trend.js +81 -0
  164. package/services/viewer/choices.js +647 -0
  165. package/services/viewer/positions.js +126 -120
  166. package/services/viewer/report-intake.js +46 -45
  167. package/test/asset-paths.test.js +28 -0
  168. package/test/audio-inventory.test.js +3 -3
  169. package/test/audio-track-bitrate.test.js +40 -0
  170. package/test/auto-quality-step.test.js +707 -515
  171. package/test/available-share.test.js +1 -1
  172. package/test/background-fill.test.js +1 -1
  173. package/test/client-log-file.test.js +110 -110
  174. package/test/completed-files.test.js +1 -1
  175. package/test/concurrent-cost.test.js +13 -3
  176. package/test/container-media-info.test.js +3 -3
  177. package/test/core-dumps.test.js +1 -1
  178. package/test/coverage-follows-the-disk.test.js +46 -9
  179. package/test/cue-push-carries-what-the-walk-found.test.js +58 -0
  180. package/test/cut-times-timeline.test.js +2 -2
  181. package/test/cuts-follow-published-grid.test.js +9 -8
  182. package/test/data-channel-frame.test.js +1 -1
  183. package/test/dead-torrent-handle.test.js +1 -1
  184. package/test/declared-rates.test.js +2 -2
  185. package/test/declared-tracks.test.js +2 -2
  186. package/test/decode-cost-fit.test.js +1 -1
  187. package/test/decode-cost.test.js +34 -25
  188. package/test/delivery-probe.test.js +1 -1
  189. package/test/demand-register.test.js +4 -4
  190. package/test/dht-bootstrap.test.js +1 -1
  191. package/test/drain-threat.test.js +65 -0
  192. package/test/duplicate-add.test.js +1 -1
  193. package/test/encode-admission.test.js +146 -0
  194. package/test/encode-cost.test.js +199 -10
  195. package/test/encode-orchestrator.test.js +39 -1
  196. package/test/encode-plan-viewers.test.js +2 -2
  197. package/test/encode-run.test.js +2 -2
  198. package/test/encode-slope.test.js +1 -1
  199. package/test/encoded-output.test.js +39 -0
  200. package/test/encoder-readings.test.js +1 -1
  201. package/test/every-claimant-is-told-its-share.test.js +152 -0
  202. package/test/failed-encoder-still-serves-what-exists.test.js +354 -0
  203. package/test/failed-start-breaker.test.js +81 -30
  204. package/test/fastest-wires.test.js +1 -1
  205. package/test/ffmpeg-stream-counts.test.js +1 -1
  206. package/test/file-edges.test.js +3 -3
  207. package/test/fmp4-self-contained.test.js +1 -1
  208. package/test/fmp4-timestamps.test.js +1 -1
  209. package/test/fmp4-track-completeness.test.js +1 -1
  210. package/test/format-keyed-outputs.test.js +78 -0
  211. package/test/health-metrics.test.js +3 -2
  212. package/test/held-request-width.test.js +22 -23
  213. package/test/helpers/encode-run.js +136 -136
  214. package/test/helpers/held-file.js +29 -0
  215. package/test/helpers/manager.js +57 -0
  216. package/test/helpers/output-spec.js +63 -0
  217. package/test/host-load.test.js +1 -1
  218. package/test/index-accuracy-is-about-the-file.test.js +128 -0
  219. package/test/init-compat.test.js +219 -0
  220. package/test/input-lost-quiets-the-plan.test.js +1 -1
  221. package/test/input-unavailable.test.js +1 -1
  222. package/test/keeping-period.test.js +4 -4
  223. package/test/keyframe-index-accuracy.test.js +97 -45
  224. package/test/keyframe-table-budget.test.js +28 -33
  225. package/test/keyframes-belong-to-the-file.test.js +174 -57
  226. package/test/learned-median.test.js +1 -1
  227. package/test/letting-go-asks-who-is-watching.test.js +191 -0
  228. package/test/limit-row-by-area.test.js +60 -0
  229. package/test/link-budget.test.js +111 -0
  230. package/test/link-probe.test.js +56 -56
  231. package/test/local-encoding-data.test.js +273 -0
  232. package/test/look-ahead-coverage.test.js +1 -1
  233. package/test/manager-surface.test.js +294 -0
  234. package/test/matroska-blocks.test.js +0 -0
  235. package/test/matroska-cues-track.test.js +1 -1
  236. package/test/memory-budget.test.js +2 -2
  237. package/test/mp4-composition-times.test.js +0 -0
  238. package/test/mp4-subtitles.test.js +1 -1
  239. package/test/one-authority.test.js +45 -41
  240. package/test/one-budget.test.js +149 -0
  241. package/test/one-output-one-session.test.js +204 -0
  242. package/test/{disk-space.test.js → one-resource-divided.test.js} +30 -10
  243. package/test/one-serving-output-per-height.test.js +458 -0
  244. package/test/orchestrator-wired.test.js +46 -45
  245. package/test/output-catalog.test.js +39 -0
  246. package/test/output-shape.test.js +4 -51
  247. package/test/output-spec.test.js +251 -157
  248. package/test/output-speed.test.js +17 -15
  249. package/test/outputs-being-prepared.test.js +40 -0
  250. package/test/packet-witness-ring.test.js +2 -2
  251. package/test/packet-witness.test.js +1 -1
  252. package/test/piece-disk-store.test.js +2 -2
  253. package/test/piece-from-whole-file.test.js +1 -1
  254. package/test/piece-lru.test.js +1 -1
  255. package/test/piece-reader.test.js +2 -2
  256. package/test/piece-store-eviction.test.js +1 -1
  257. package/test/piece-store-never-refuses.test.js +1 -1
  258. package/test/piece-store-reservations.test.js +1 -1
  259. package/test/piece-store-slow-disk.test.js +1 -1
  260. package/test/piece-tail.test.js +1 -1
  261. package/test/plan-host-timings.test.js +1 -1
  262. package/test/plan-is-steady.test.js +225 -225
  263. package/test/priority-map-download.test.js +4 -4
  264. package/test/priority-map-emptied.test.js +204 -205
  265. package/test/priority-map-per-output.test.js +215 -209
  266. package/test/priority-map.test.js +1 -1
  267. package/test/probe-wedge-certainty.test.js +1 -1
  268. package/test/produced-copy-choice.test.js +15 -60
  269. package/test/quality-offer.test.js +162 -0
  270. package/test/quality-variants.test.js +1229 -1167
  271. package/test/rate-control-in-the-output.test.js +180 -0
  272. package/test/read-survives-withdrawal.test.js +2 -2
  273. package/test/read-window.test.js +10 -3
  274. package/test/resume-warm.test.js +1 -1
  275. package/test/run-inputs.test.js +80 -0
  276. package/test/run-position-follows-published-grid.test.js +13 -11
  277. package/test/run-progress.test.js +65 -0
  278. package/test/same-height-switch.test.js +664 -0
  279. package/test/seek-frees-the-viewers-requests.test.js +217 -0
  280. package/test/seek-landing.test.js +13 -13
  281. package/test/seek-target-not-superseded.test.js +28 -29
  282. package/test/segment-closed-on-both-branches.test.js +96 -0
  283. package/test/segment-cut-times.test.js +1 -1
  284. package/test/segment-hold-supersede.test.js +28 -35
  285. package/test/segment-judged-by-its-own-header.test.js +221 -0
  286. package/test/segment-serve-wiring.test.js +130 -39
  287. package/test/segment-store-eviction.test.js +22 -7
  288. package/test/segment-store.test.js +98 -14
  289. package/test/segment-true-start.test.js +1 -1
  290. package/test/segments-are-shared.test.js +17 -16
  291. package/test/send-chunk-bytes.test.js +1 -1
  292. package/test/serving-existing-output.test.js +102 -0
  293. package/test/serving-output.test.js +102 -0
  294. package/test/shared-piece-store.test.js +1 -1
  295. package/test/source-file.test.js +1 -1
  296. package/test/stale-request-after-seek.test.js +17 -21
  297. package/test/startup-readings.test.js +10 -5
  298. package/test/subtitle-cue-framing.test.js +5 -5
  299. package/test/subtitle-cue-source.test.js +36 -38
  300. package/test/subtitle-cue-walk.test.js +11 -10
  301. package/test/subtitle-defaults.test.js +1 -1
  302. package/test/subtitle-language.test.js +4 -4
  303. package/test/subtitle-track-numbering.test.js +5 -4
  304. package/test/supply-margin.test.js +1 -1
  305. package/test/swarm-follows-readers.test.js +3 -3
  306. package/test/swarm-reach.test.js +1 -1
  307. package/test/swarm-selection.test.js +3 -3
  308. package/test/tail-duplication.test.js +1 -1
  309. package/test/the-channel-has-both-ends.test.js +91 -0
  310. package/test/the-torrent-thread-serves-bytes.test.js +107 -0
  311. package/test/thread-pool.test.js +3 -3
  312. package/test/timeline.test.js +1 -12
  313. package/test/torrent-cost.test.js +1 -1
  314. package/test/tracks-begin-together.test.js +38 -24
  315. package/test/tunnel-renewal.test.js +1 -1
  316. package/test/two-viewers-one-picture.test.js +120 -87
  317. package/test/upload-hurry.test.js +3 -3
  318. package/test/usrsctp-state.test.js +1 -1
  319. package/test/video-facts.test.js +1 -1
  320. package/test/viewer-assignments.test.js +143 -0
  321. package/test/viewer-outputs.test.js +60 -52
  322. package/test/viewer-presence.test.js +22 -25
  323. package/test/viewer-requests-admission.test.js +89 -0
  324. package/test/viewer-states.test.js +189 -202
  325. package/test/viewer-subtitle-subscription.test.js +1 -1
  326. package/test/viewer.test.js +139 -136
  327. package/test/viewing-generations.test.js +390 -0
  328. package/test/visible-rung.test.js +37 -0
  329. package/test/wait-ledger.test.js +1 -1
  330. package/test/webrtc-shim.test.js +3 -3
  331. package/test/wedge-certainty.test.js +2 -2
  332. package/test/withdraw-piece-claim.test.js +2 -2
  333. package/test/worker-channel.test.js +1 -31
  334. package/utils/client-log-file.js +151 -151
  335. package/scripts/read-container-index.mjs +0 -108
  336. package/services/container/ContainerFactory.js +0 -122
  337. package/services/controllers/PlaybackController.js +0 -33
  338. package/services/disk/DiskSpace.js +0 -150
  339. package/services/disk/wire.js +0 -61
  340. package/services/hls-session-manager.js +0 -9608
  341. package/services/orchestrators/SubtitleOrchestrator.js +0 -160
  342. package/services/output/Output.js +0 -94
  343. package/services/output/OutputSpec.js +0 -202
  344. package/services/output/index.js +0 -1
  345. package/services/output/ladder.js +0 -26
  346. package/services/produced-index.js +0 -222
  347. package/services/quality/EncodeCost.js +0 -555
  348. package/services/torrent-worker/container-tracks.js +0 -414
  349. package/services/viewer/link-readings.js +0 -56
  350. package/test/produced-index.test.js +0 -142
  351. /package/{services → bin}/thread-pool.js +0 -0
  352. /package/services/{available-share.js → encode/available-share.js} +0 -0
  353. /package/services/{decode-cost-fit.js → encode/decode-cost-fit.js} +0 -0
  354. /package/services/{encoder-readings.js → encode/encoder-readings.js} +0 -0
  355. /package/services/{host-load.js → encode/host-load.js} +0 -0
  356. /package/services/{output → encode/output}/cut-grid.js +0 -0
  357. /package/services/{output → encode/output}/rates.js +0 -0
  358. /package/services/{segment-formats → encode/segment-formats}/mpegts.js +0 -0
  359. /package/services/{torrent-cost.js → encode/torrent-cost.js} +0 -0
  360. /package/services/{container → media/container}/ebml-reader.js +0 -0
  361. /package/services/{ffmpeg-banner.js → media/ffmpeg-banner.js} +0 -0
  362. /package/services/{tracks → media/tracks}/ContainerTrack.js +0 -0
  363. /package/services/{tracks → media/tracks}/ImageSubtitleTrack.js +0 -0
  364. /package/services/{tracks → media/tracks}/SubtitleTrack.js +0 -0
  365. /package/services/{tracks → media/tracks}/TextSubtitleTrack.js +0 -0
  366. /package/services/{tracks → media/tracks}/VideoTrack.js +0 -0
  367. /package/services/{tracks → media/tracks}/index.js +0 -0
  368. /package/services/{files → storage/files}/piece-from-whole-file.js +0 -0
  369. /package/services/{disk → storage}/keep.js +0 -0
  370. /package/services/{piece-store → storage/piece-store}/piece-lru.js +0 -0
  371. /package/services/{disk → storage}/returns.js +0 -0
  372. /package/services/{demand → torrent/demand}/DemandRegister.js +0 -0
  373. /package/services/{demand → torrent/demand}/Urgency.js +0 -0
  374. /package/services/{demand → torrent/demand}/Window.js +0 -0
  375. /package/services/{demand → torrent/demand}/index.js +0 -0
  376. /package/services/{demand → torrent/demand}/pieces.js +0 -0
  377. /package/services/{download → torrent/download}/withdraw-claim.js +0 -0
  378. /package/services/{supply-margin.js → torrent/supply-margin.js} +0 -0
  379. /package/services/{torrent-source-key.js → torrent/torrent-source-key.js} +0 -0
  380. /package/services/{torrent-worker → torrent/worker}/fastest-wires.js +0 -0
  381. /package/services/{torrent-worker → torrent/worker}/handle-state.js +0 -0
  382. /package/services/{nat-classifier.js → transport/nat-classifier.js} +0 -0
  383. /package/services/{registry-api.js → transport/registry-api.js} +0 -0
  384. /package/services/{tunnel-client.js → transport/tunnel-client.js} +0 -0
  385. /package/services/{priority → viewer}/WaitLedger.js +0 -0
@@ -1,94 +1,129 @@
1
- import { recordViewerReport } from "../../../../services/viewer/report-intake.js";
2
-
3
- /**
4
- * Accept a viewer link report for a transcode session (adaptive bitrate).
5
- * The browser measures its own data-channel throughput per segment fetch and
6
- * posts a rolling median + its buffered seconds; the session manager's budget
7
- * loop uses the latest report as the link-deficit downshift trigger.
8
- *
9
- * POST /api/transcode-sessions/:sessionId/net-report
10
- * Body: { linkMbps: number, bufferedAheadSec: number,
11
- * consumerId?: string, positionSeconds?: number }
12
- *
13
- * `consumerId` and `positionSeconds` say WHO is reporting and WHERE they are.
14
- * A copied picture is one session shared by every viewer of it, so without them
15
- * the proxy could only act on whichever viewer reported last. Both are
16
- * optional: a browser that sends neither is treated exactly as before.
17
- *
18
- * Best-effort telemetry: invalid body → 400, unknown session → 404, ok → 204.
19
- *
20
- * @param {import("fastify").FastifyRequest} req
21
- * @param {import("fastify").FastifyReply} reply
22
- * @param {{ sessions: { get: (id: string) => object | undefined }, viewers: object }} deps -
23
- * The live sessions and the registry of viewers. The VIEWER layer takes the
24
- * statement from here; this route's whole job is turning a request into that
25
- * one call and its answer into a status code.
26
- * @returns {Promise<void>}
27
- */
28
- export async function handleApiTranscodeSessionNetReportPost(req, reply, { sessions, viewers }) {
29
- const sessionId = typeof req.params.sessionId === "string" ? req.params.sessionId : "";
30
- const body = req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : {};
31
- // WHAT THIS REPORT IS. A statement by one viewer about itself: where the
32
- // picture is, how much film it holds, whether it is moving, whether it is
33
- // blocked on us, whether the page is on screen — and, when there has been
34
- // anything to measure, how fast the link carried it.
35
- //
36
- // THE LINK FIGURE IS NOT REQUIRED, and requiring it is the fault of
37
- // 2026-09-14. A page measures its link from completed transfers, so a page
38
- // that has not yet been delivered a segment has no figure; at a cold open
39
- // that is every page. Rejected here with 400, the page's own account of
40
- // itself never arrived, this proxy filled the silence by assuming the film
41
- // was running, and a viewer who had not seen a frame was placed 146 seconds
42
- // into it — the soundtrack's encoder went there, and the segment the browser
43
- // was actually asking for was ranked last of a hundred and answered 503.
44
- const linkMbps = Number(body.linkMbps);
45
- const bufferedAheadSec = Number(body.bufferedAheadSec);
46
- if (!sessionId || !Number.isFinite(bufferedAheadSec) || bufferedAheadSec < 0) {
47
- return reply.code(400).send({ error: "bufferedAheadSec (>=0) is required." });
48
- }
49
-
50
- // Neither is required, and neither can make a report invalid: they are what
51
- // the proxy uses to tell the viewers of one session apart, and a report
52
- // without them is still a truthful reading of somebody's link.
53
- const consumerId = typeof body.consumerId === "string" ? body.consumerId.trim() : "";
54
- // Whether the picture is moving. Absent from a page that does not say, and
55
- // then nothing is assumed: a statement about somebody else's machine is
56
- // theirs to make, and assuming it walked a viewer 146 seconds into a film
57
- // they had not begun (2026-09-14).
58
- const playing = typeof body.playing === "boolean" ? body.playing : undefined;
59
- // Whether this viewer is BLOCKED on material we owe them, which is a
60
- // different state from having stopped the picture: the first is the most
61
- // urgent viewer there is, the second consumes nothing and can wait. One
62
- // boolean could not hold three states and read the first as the second.
63
- const waiting = typeof body.waiting === "boolean" ? body.waiting : undefined;
64
- // Whether the page is on screen, and whether the picture was pulled out of
65
- // it. A hidden tab has its timers throttled, so it asks for nothing and looks
66
- // exactly like a viewer holding a full cushion; picture-in-picture is the case
67
- // that makes the distinction necessary, because there the tab is hidden and
68
- // the viewer is watching. Absent from a page that does not say, and then the
69
- // viewer is on screen, as every page meant before it could say otherwise.
70
- const onScreen = typeof body.onScreen === "boolean" ? body.onScreen : undefined;
71
- const inPictureInPicture =
72
- typeof body.inPictureInPicture === "boolean" ? body.inPictureInPicture : undefined;
73
- const positionSeconds = Number(body.positionSeconds);
74
- const recorded = recordViewerReport({
75
- sessions,
76
- viewers,
77
- sessionId,
78
- report: {
79
- linkMbps: Number.isFinite(linkMbps) && linkMbps > 0 ? linkMbps : undefined,
80
- bufferedAheadSec,
81
- consumerId,
82
- playing,
83
- waiting,
84
- onScreen,
85
- inPictureInPicture,
86
- positionSeconds:
87
- Number.isFinite(positionSeconds) && positionSeconds >= 0 ? positionSeconds : undefined
88
- }
89
- });
90
- if (!recorded) {
91
- return reply.code(404).send({ error: "Transcode session was not found." });
92
- }
93
- return reply.code(204).send();
94
- }
1
+ import { recordViewerReport } from "../../../../services/viewer/report-intake.js";
2
+
3
+ /**
4
+ * Accept a viewer link report for a transcode session (adaptive bitrate).
5
+ * The browser measures its own data-channel throughput per segment fetch and
6
+ * posts a rolling median + its buffered seconds; the session manager's budget
7
+ * loop uses the latest report as the link-deficit downshift trigger.
8
+ *
9
+ * POST /api/transcode-sessions/:sessionId/net-report
10
+ * Body: { consumerId: string, bufferedAheadSec: number, linkMbps?: number,
11
+ * positionSeconds?: number, playingHeight?: number, … }
12
+ *
13
+ * `consumerId` and `positionSeconds` say WHO is reporting and WHERE they are.
14
+ * A copied picture is one session shared by every viewer of it, so without them
15
+ * the proxy could only act on whichever viewer reported last. The viewer is
16
+ * required; the position is not.
17
+ *
18
+ * Best-effort telemetry: invalid body → 400, unknown session → 404, ok → 204.
19
+ *
20
+ * @param {import("fastify").FastifyRequest} req
21
+ * @param {import("fastify").FastifyReply} reply
22
+ * @param {{ outputs: { get: (id: string) => object | undefined }, viewers: object, renditions: { viewerPlays: Function, noteViewerReported: Function }, quality: { noteViewerReported: Function } }} deps -
23
+ * The live outputs, the registry of viewers, and the rungs of a picture. The
24
+ * VIEWER component takes the statement; which rung a stated height is, is the
25
+ * encoding component's. This route's whole job is turning a request into
26
+ * those calls and their answer into a status code.
27
+ * @returns {Promise<void>}
28
+ */
29
+ export async function handleApiTranscodeSessionNetReportPost(req, reply, { outputs, viewers, renditions, quality }) {
30
+ const sessionId = typeof req.params.sessionId === "string" ? req.params.sessionId : "";
31
+ const body = req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : {};
32
+ // WHAT THIS REPORT IS. A statement by one viewer about itself: where the
33
+ // picture is, how much film it holds, whether it is moving, whether it is
34
+ // blocked on us, whether the page is on screen — and, when there has been
35
+ // anything to measure, how fast the link carried it.
36
+ //
37
+ // THE LINK FIGURE IS NOT REQUIRED, and requiring it is the fault of
38
+ // 2026-09-14. A page measures its link from completed transfers, so a page
39
+ // that has not yet been delivered a segment has no figure; at a cold open
40
+ // that is every page. Rejected here with 400, the page's own account of
41
+ // itself never arrived, this proxy filled the silence by assuming the film
42
+ // was running, and a viewer who had not seen a frame was placed 146 seconds
43
+ // into it — the soundtrack's encoder went there, and the segment the browser
44
+ // was actually asking for was ranked last of a hundred and answered 503.
45
+ const linkMbps = Number(body.linkMbps);
46
+ const bufferedAheadSec = Number(body.bufferedAheadSec);
47
+ if (!sessionId || !Number.isFinite(bufferedAheadSec) || bufferedAheadSec < 0) {
48
+ return reply.code(400).send({ error: "bufferedAheadSec (>=0) is required." });
49
+ }
50
+
51
+ // WHO is reporting is required: a viewer always has a name, and a reading of
52
+ // a link that belongs to nobody cannot be kept anywhere. The position is not
53
+ // required — a report without one is still a truthful reading of that link.
54
+ const consumerId = typeof body.consumerId === "string" ? body.consumerId.trim() : "";
55
+ if (!consumerId) {
56
+ return reply.code(400).send({ error: "consumerId is required." });
57
+ }
58
+ // Whether the picture is moving. Absent from a page that does not say, and
59
+ // then nothing is assumed: a statement about somebody else's machine is
60
+ // theirs to make, and assuming it walked a viewer 146 seconds into a film
61
+ // they had not begun (2026-09-14).
62
+ const playing = typeof body.playing === "boolean" ? body.playing : undefined;
63
+ // Whether this viewer is BLOCKED on material we owe them, which is a
64
+ // different state from having stopped the picture: the first is the most
65
+ // urgent viewer there is, the second consumes nothing and can wait. One
66
+ // boolean could not hold three states and read the first as the second.
67
+ const waiting = typeof body.waiting === "boolean" ? body.waiting : undefined;
68
+ // Whether the page is on screen, and whether the picture was pulled out of
69
+ // it. A hidden tab has its timers throttled, so it asks for nothing and looks
70
+ // exactly like a viewer holding a full cushion; picture-in-picture is the case
71
+ // that makes the distinction necessary, because there the tab is hidden and
72
+ // the viewer is watching. Absent from a page that does not say, and then the
73
+ // viewer is on screen, as every page meant before it could say otherwise.
74
+ const onScreen = typeof body.onScreen === "boolean" ? body.onScreen : undefined;
75
+ const inPictureInPicture =
76
+ typeof body.inPictureInPicture === "boolean" ? body.inPictureInPicture : undefined;
77
+ // Whether the size on screen was picked by hand or is the automatic choice.
78
+ // A size picked by hand is served exactly; the automatic choice may be served
79
+ // by an output of the same quality or better that is already made.
80
+ const qualityMode = body.qualityMode === "auto" || body.qualityMode === "manual" ? body.qualityMode : undefined;
81
+ const positionSeconds = Number(body.positionSeconds);
82
+ // The picture as the viewer sees it, in physical pixels: the upper bound of
83
+ // the height of a re-encoded output made for them (roadmap item 98). Sent the
84
+ // moment it changes; a page that does not say leaves the size as it was.
85
+ const visiblePicture = body.visiblePicture && typeof body.visiblePicture === "object"
86
+ ? { width: Number(body.visiblePicture.width), height: Number(body.visiblePicture.height) }
87
+ : undefined;
88
+ // WHICH RUNG THE PLAYER IS PLAYING, stated by the page the moment it
89
+ // switched. Stated before the report is recorded, because the report belongs
90
+ // to the rung on screen. A page that does not say leaves the rung as it was.
91
+ const playingHeight = Number(body.playingHeight);
92
+ if (Number.isInteger(playingHeight) && playingHeight > 0) {
93
+ renditions.viewerPlays(
94
+ sessionId,
95
+ consumerId,
96
+ playingHeight,
97
+ Number.isFinite(positionSeconds) && positionSeconds >= 0 ? positionSeconds : undefined
98
+ );
99
+ }
100
+ const recorded = recordViewerReport({
101
+ outputs,
102
+ viewers,
103
+ sessionId,
104
+ report: {
105
+ linkMbps: Number.isFinite(linkMbps) && linkMbps > 0 ? linkMbps : undefined,
106
+ bufferedAheadSec,
107
+ consumerId,
108
+ playing,
109
+ waiting,
110
+ onScreen,
111
+ inPictureInPicture,
112
+ qualityMode,
113
+ visiblePicture,
114
+ positionSeconds:
115
+ Number.isFinite(positionSeconds) && positionSeconds >= 0 ? positionSeconds : undefined
116
+ }
117
+ });
118
+ if (!recorded) {
119
+ return reply.code(404).send({ error: "Transcode session was not found." });
120
+ }
121
+ // After the statement is recorded, so what is judged is what they just said:
122
+ // a move of theirs to another limit may no longer be wanted.
123
+ renditions.noteViewerReported(sessionId, consumerId);
124
+ // And the quality budget judges this viewer now, on what they just said —
125
+ // their buffer's trend, their link, the picture they see — rather than at
126
+ // the next tick of a timer.
127
+ void quality.noteViewerReported(sessionId, consumerId);
128
+ return reply.code(204).send();
129
+ }
@@ -1,139 +1,160 @@
1
- /**
2
- * Create or return an existing HLS transcode session for a torrent file.
3
- *
4
- * POST /api/transcode-sessions
5
- *
6
- * @param {import("fastify").FastifyRequest} req
7
- * @param {import("fastify").FastifyReply} reply
8
- * @param {{ hlsSessionManager: import("../../../services/hls-session-manager.js").HlsSessionManager, sourceRegistry: object, torrentPool: object }} deps
9
- * @returns {Promise<void>}
10
- */
11
-
12
- import { logger } from "../../../utils/logger.js";
13
-
14
- /**
15
- * Extract a plain object from the request body, guarding against
16
- * non-object payloads (arrays, primitives, null).
17
- *
18
- * @param {unknown} body
19
- * @returns {Record<string, unknown>}
20
- */
21
- function getPayload(body) {
22
- if (body && typeof body === "object" && !Array.isArray(body)) {
23
- return body;
24
- }
25
- return {};
26
- }
27
-
28
-
29
- export async function handleApiTranscodeSessionsPost(req, reply, { hlsSessionManager, sourceRegistry, torrentPool }) {
30
- const payload = getPayload(req.body);
31
- const sourceKey = typeof payload.sourceKey === "string" ? payload.sourceKey.trim() : "";
32
- const fileIndex = Number(payload.fileIndex);
33
- const transcodeVideo = payload.transcodeVideo === true;
34
- const transcodeAudio = payload.transcodeAudio === true;
35
- const consumerId = typeof payload.consumerId === "string" ? payload.consumerId.trim() : "";
36
- const fileName = typeof payload.fileName === "string" ? payload.fileName.trim() : "";
37
- const targetWidth = Number(payload.targetWidth);
38
- const targetHeight = Number(payload.targetHeight);
39
- // The target box is produced exactly (capped to source), with the realtime
40
- // budget's auto-downscale and runtime downswitch off for this session.
41
- //
42
- // It says nothing about WHO asked — a rung sets it whether the viewer picked
43
- // that rung or the player moved itself onto one.
44
- const exactSize = payload.exactSize === true;
45
- // Whether this browser will take its audio from a separate rendition group in
46
- // the master playlist rather than muxed into the picture. It has to say so:
47
- // publishing renditions AND muxing the same audio would play it twice, while
48
- // a browser that does not know about them would get no sound at all.
49
- const audioRenditions = payload.audioRenditions === true;
50
- const startPositionSeconds = Number(payload.startPositionSeconds);
51
- const audioTrackIndex = Number(payload.audioTrackIndex);
52
- // Which container to produce. The browser knows what its media stack will
53
- // accept for the tracks it asked to be copied; an absent or unknown value
54
- // leaves the proxy's own `--segment-format` in charge.
55
- const segmentFormatId =
56
- typeof payload.segmentFormat === "string" ? payload.segmentFormat.trim() : "";
57
-
58
- if (!sourceKey || !Number.isInteger(fileIndex) || fileIndex < 0) {
59
- return reply.code(400).send({ error: "sourceKey and valid fileIndex are required." });
60
- }
61
-
62
- try {
63
- const session = await hlsSessionManager.createOrGetSession({
64
- sourceKey,
65
- fileIndex,
66
- transcodeVideo,
67
- transcodeAudio,
68
- consumerId,
69
- fileName,
70
- targetWidth: Number.isInteger(targetWidth) && targetWidth > 0 ? targetWidth : 0,
71
- targetHeight: Number.isInteger(targetHeight) && targetHeight > 0 ? targetHeight : 0,
72
- exactSize,
73
- audioRenditions,
74
- startPositionSeconds:
75
- Number.isFinite(startPositionSeconds) && startPositionSeconds > 0
76
- ? startPositionSeconds
77
- : 0,
78
- audioTrackIndex:
79
- Number.isInteger(audioTrackIndex) && audioTrackIndex > 0 ? audioTrackIndex : 0,
80
- segmentFormatId
81
- });
82
- // The index of quality variants, when this session has more than one to
83
- // offer. Its presence is what tells the browser it can change quality
84
- // without a new session: the player switches variants itself, appending the
85
- // new one after what is already buffered. Absent for a copied video, whose
86
- // segments are cut at the source's own keyframes and so cannot be spliced
87
- // with a re-encoded rung.
88
- const hasVariants = hlsSessionManager.buildMasterPlaylist(session.id) !== null;
89
- return reply.send({
90
- sessionId: session.id,
91
- playlistPath: `/transcode/${session.id}/index.m3u8`,
92
- ...(hasVariants
93
- ? {
94
- masterPath: `/transcode/${session.id}/master.m3u8`,
95
- // Which of the master's variants this session IS. The browser pins
96
- // the player to it, so loading the master costs nothing: an encoder
97
- // is already producing that height, and any other rung would be a
98
- // second cold start before the first frame.
99
- variantHeight: hlsSessionManager.liveOutputs.variantHeightOf(session)
100
- }
101
- : {}),
102
- // The heights this host will actually serve this file at, largest first
103
- // — the ladder minus every rung it cannot produce faster than it is
104
- // watched. The browser needs it whether or not a master exists: without
105
- // it, it fell back to a ladder of its own invention and offered rungs the
106
- // proxy had just refused, and picking one re-opened the session at a
107
- // height measured at a third of realtime.
108
- offeredHeights: hlsSessionManager.offeredHeights(session),
109
- // What this session's output will carry, stated rather than left to be
110
- // discovered. The browser checks what it actually got against this: a
111
- // track that never arrives is otherwise noticed only by its absence,
112
- // minutes later, as a black picture with working sound.
113
- tracks: hlsSessionManager.declaredTracks(session),
114
- // How far ahead of the viewer this proxy lets the encoder run, in seconds
115
- // of playback. The browser sizes its own forward buffer from it, so the
116
- // two sides agree by construction instead of each carrying a constant of
117
- // its own — which is how the browser came to hold thirty seconds while
118
- // two minutes stood produced on disk (roadmap item 4).
119
- lookaheadSeconds: hlsSessionManager.lookaheadSeconds
120
- });
121
- } catch (error) {
122
- if (error instanceof Error && error.code === "TRANSCODE_DISABLED") {
123
- return reply.code(409).send({ error: error.message });
124
- }
125
- const message = error instanceof Error ? error.message : String(error);
126
- // Say why on the proxy's own log, not only in the answer. This route
127
- // answered 500 for every viewer of proxy 2.9.101-2.9.102 (an undeclared
128
- // constant) and the addon log carried nothing but the data-channel layer's
129
- // bare "→ 500": the cause had to be recovered by replaying the request
130
- // against the live proxy. The stack is worth the two lines it costs — a
131
- // programming error here is invisible to the viewer, who only sees that
132
- // nothing plays.
133
- logger.error(
134
- `transcode-sessions: ${sourceKey}:${fileIndex} failed to prepare: ${message}\n` +
135
- `${error instanceof Error ? (error.stack ?? "") : ""}`
136
- );
137
- return reply.code(500).send({ error: `Failed to prepare transcode session: ${message}` });
138
- }
139
- }
1
+ /**
2
+ * Create or return an existing HLS transcode session for a torrent file.
3
+ *
4
+ * POST /api/transcode-sessions
5
+ *
6
+ * @param {import("fastify").FastifyRequest} req
7
+ * @param {import("fastify").FastifyReply} reply
8
+ * @param {{ viewerRequests: object, renditions: object, quality: object, outputs: object, lookaheadSeconds: number, sourceRegistry: object, torrentPool: object }} deps
9
+ * @returns {Promise<void>}
10
+ */
11
+
12
+ import { logger } from "../../../utils/logger.js";
13
+ import { OUTPUT_NO_CAPACITY, OUTPUT_UNAVAILABLE } from "../../../services/encode/output/index.js";
14
+ import { replyNoCapacity, replyOutputUnavailable } from "../../../services/server/http-responses.js";
15
+
16
+ /**
17
+ * Extract a plain object from the request body, guarding against
18
+ * non-object payloads (arrays, primitives, null).
19
+ *
20
+ * @param {unknown} body
21
+ * @returns {Record<string, unknown>}
22
+ */
23
+ function getPayload(body) {
24
+ if (body && typeof body === "object" && !Array.isArray(body)) {
25
+ return body;
26
+ }
27
+ return {};
28
+ }
29
+
30
+
31
+ export async function handleApiTranscodeSessionsPost(req, reply, { viewerRequests, renditions, quality, outputs, lookaheadSeconds, sourceRegistry, torrentPool }) {
32
+ const payload = getPayload(req.body);
33
+ const sourceKey = typeof payload.sourceKey === "string" ? payload.sourceKey.trim() : "";
34
+ const fileIndex = Number(payload.fileIndex);
35
+ const transcodeVideo = payload.transcodeVideo === true;
36
+ const transcodeAudio = payload.transcodeAudio === true;
37
+ const consumerId = typeof payload.consumerId === "string" ? payload.consumerId.trim() : "";
38
+ const fileName = typeof payload.fileName === "string" ? payload.fileName.trim() : "";
39
+ const targetWidth = Number(payload.targetWidth);
40
+ const targetHeight = Number(payload.targetHeight);
41
+ // The picture as the viewer sees it, in physical pixels. For a re-encoded
42
+ // picture the height made is the smallest rung whose frame is not smaller
43
+ // than this (roadmap item 98); it takes the place of a target box.
44
+ const visibleWidth = Number(payload.visiblePicture?.width);
45
+ const visibleHeight = Number(payload.visiblePicture?.height);
46
+ const visiblePicture = visibleWidth > 0 && visibleHeight > 0
47
+ ? { width: Math.round(visibleWidth), height: Math.round(visibleHeight) }
48
+ : null;
49
+ // The target box is produced exactly (capped to source), with the realtime
50
+ // budget's auto-downscale and runtime downswitch off for this session.
51
+ //
52
+ // It says nothing about WHO asked — a rung sets it whether the viewer picked
53
+ // that rung or the player moved itself onto one.
54
+ const exactSize = payload.exactSize === true;
55
+ // Whether this browser will take its audio from a separate rendition group in
56
+ // the master playlist rather than muxed into the picture. It has to say so:
57
+ // publishing renditions AND muxing the same audio would play it twice, while
58
+ // a browser that does not know about them would get no sound at all.
59
+ const audioRenditions = payload.audioRenditions === true;
60
+ const startPositionSeconds = Number(payload.startPositionSeconds);
61
+ const audioTrackIndex = Number(payload.audioTrackIndex);
62
+ // Which container to produce. The browser knows what its media stack will
63
+ // accept for the tracks it asked to be copied; an absent or unknown value
64
+ // leaves the proxy's own `--segment-format` in charge.
65
+ const segmentFormatId =
66
+ typeof payload.segmentFormat === "string" ? payload.segmentFormat.trim() : "";
67
+
68
+ if (!sourceKey || !Number.isInteger(fileIndex) || fileIndex < 0) {
69
+ return reply.code(400).send({ error: "sourceKey and valid fileIndex are required." });
70
+ }
71
+ // The output is opened FOR somebody, and a viewer always has a name.
72
+ if (!consumerId) {
73
+ return reply.code(400).send({ error: "consumerId is required." });
74
+ }
75
+
76
+ try {
77
+ const session = await viewerRequests.createOrGetSession({
78
+ sourceKey,
79
+ fileIndex,
80
+ transcodeVideo,
81
+ transcodeAudio,
82
+ consumerId,
83
+ fileName,
84
+ targetWidth: Number.isInteger(targetWidth) && targetWidth > 0 ? targetWidth : 0,
85
+ targetHeight: Number.isInteger(targetHeight) && targetHeight > 0 ? targetHeight : 0,
86
+ exactSize,
87
+ visiblePicture,
88
+ audioRenditions,
89
+ startPositionSeconds:
90
+ Number.isFinite(startPositionSeconds) && startPositionSeconds > 0
91
+ ? startPositionSeconds
92
+ : 0,
93
+ audioTrackIndex:
94
+ Number.isInteger(audioTrackIndex) && audioTrackIndex > 0 ? audioTrackIndex : 0,
95
+ segmentFormatId
96
+ });
97
+ // The index of quality variants, when this session has more than one to
98
+ // offer. Its presence is what tells the browser it can change quality
99
+ // without a new session: the player switches variants itself, appending the
100
+ // new one after what is already buffered. Absent for a copied video, whose
101
+ // segments are cut at the source's own keyframes and so cannot be spliced
102
+ // with a re-encoded rung.
103
+ const hasVariants = renditions.buildMasterPlaylist(session.id) !== null;
104
+ return reply.send({
105
+ sessionId: session.id,
106
+ playlistPath: `/transcode/${session.id}/index.m3u8`,
107
+ ...(hasVariants
108
+ ? {
109
+ masterPath: `/transcode/${session.id}/master.m3u8`,
110
+ // Which of the master's variants this session IS. The browser pins
111
+ // the player to it, so loading the master costs nothing: an encoder
112
+ // is already producing that height, and any other rung would be a
113
+ // second cold start before the first frame.
114
+ variantHeight: outputs.variantHeightOf(session)
115
+ }
116
+ : {}),
117
+ // The heights this host will actually serve this file at, largest first
118
+ // — the ladder minus every rung it cannot produce faster than it is
119
+ // watched. The browser needs it whether or not a master exists: without
120
+ // it, it fell back to a ladder of its own invention and offered rungs the
121
+ // proxy had just refused, and picking one re-opened the session at a
122
+ // height measured at a third of realtime.
123
+ offeredHeights: quality.offeredHeights(session),
124
+ // What this session's output will carry, stated rather than left to be
125
+ // discovered. The browser checks what it actually got against this: a
126
+ // track that never arrives is otherwise noticed only by its absence,
127
+ // minutes later, as a black picture with working sound.
128
+ tracks: renditions.declaredTracks(session),
129
+ // How far ahead of the viewer this proxy lets the encoder run, in seconds
130
+ // of playback. The browser sizes its own forward buffer from it, so the
131
+ // two sides agree by construction instead of each carrying a constant of
132
+ // its own — which is how the browser came to hold thirty seconds while
133
+ // two minutes stood produced on disk (roadmap item 4).
134
+ lookaheadSeconds: lookaheadSeconds
135
+ });
136
+ } catch (error) {
137
+ if (error instanceof Error && error.code === "TRANSCODE_DISABLED") {
138
+ return reply.code(409).send({ error: error.message });
139
+ }
140
+ if (error?.code === OUTPUT_UNAVAILABLE) {
141
+ return replyOutputUnavailable(reply, error.details);
142
+ }
143
+ if (error?.code === OUTPUT_NO_CAPACITY) {
144
+ return replyNoCapacity(reply, error.details);
145
+ }
146
+ const message = error instanceof Error ? error.message : String(error);
147
+ // Say why on the proxy's own log, not only in the answer. This route
148
+ // answered 500 for every viewer of proxy 2.9.101-2.9.102 (an undeclared
149
+ // constant) and the addon log carried nothing but the data-channel layer's
150
+ // bare "→ 500": the cause had to be recovered by replaying the request
151
+ // against the live proxy. The stack is worth the two lines it costs — a
152
+ // programming error here is invisible to the viewer, who only sees that
153
+ // nothing plays.
154
+ logger.error(
155
+ `transcode-sessions: ${sourceKey}:${fileIndex} failed to prepare: ${message}\n` +
156
+ `${error instanceof Error ? (error.stack ?? "") : ""}`
157
+ );
158
+ return reply.code(500).send({ error: `Failed to prepare transcode session: ${message}` });
159
+ }
160
+ }
@@ -5,10 +5,10 @@
5
5
  *
6
6
  * @param {import("fastify").FastifyRequest} req
7
7
  * @param {import("fastify").FastifyReply} reply
8
- * @param {{ hlsSessionManager: import("../../../../services/hls-session-manager.js").HlsSessionManager }} deps
8
+ * @param {{ viewerRequests: object }} deps
9
9
  * @returns {Promise<void>}
10
10
  */
11
- export async function handleApiTranscodeSessionsProgressGet(req, reply, { hlsSessionManager }) {
11
+ export async function handleApiTranscodeSessionsProgressGet(req, reply, { viewerRequests }) {
12
12
  const sessionId = typeof req.params.sessionId === "string" ? req.params.sessionId : "";
13
13
  if (!sessionId) {
14
14
  return reply.code(400).send({ error: "sessionId is required." });
@@ -18,7 +18,7 @@ export async function handleApiTranscodeSessionsProgressGet(req, reply, { hlsSes
18
18
  // quality change the stream on screen is another session — a different one
19
19
  // for each viewer who changed.
20
20
  const consumerId = typeof req.query?.consumer === "string" ? req.query.consumer : "";
21
- const progress = await hlsSessionManager.getSessionProgress(sessionId, consumerId);
21
+ const progress = await viewerRequests.getSessionProgress(sessionId, consumerId);
22
22
  if (!progress) {
23
23
  return reply.code(404).send({ error: "Transcode session was not found." });
24
24
  }
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @param {import("fastify").FastifyRequest} req
8
8
  * @param {import("fastify").FastifyReply} reply
9
- * @param {{ hlsSessionManager: import("../../../../services/hls-session-manager.js").HlsSessionManager }} deps
9
+ * @param {{ lifecycle: object }} deps
10
10
  * @returns {Promise<void>}
11
11
  */
12
12
 
@@ -24,7 +24,7 @@ function getPayload(body) {
24
24
  return {};
25
25
  }
26
26
 
27
- export async function handleApiTranscodeSessionReleasePost(req, reply, { hlsSessionManager }) {
27
+ export async function handleApiTranscodeSessionReleasePost(req, reply, { lifecycle }) {
28
28
  const sessionId = typeof req.params.sessionId === "string" ? req.params.sessionId : "";
29
29
  const payload = getPayload(req.body);
30
30
  const consumerId = typeof payload.consumerId === "string" ? payload.consumerId.trim() : "";
@@ -33,7 +33,7 @@ export async function handleApiTranscodeSessionReleasePost(req, reply, { hlsSess
33
33
  return reply.code(400).send({ error: "sessionId and consumerId are required." });
34
34
  }
35
35
 
36
- const released = await hlsSessionManager.releaseSessionConsumer(sessionId, consumerId, reason);
36
+ const released = await lifecycle.releaseSessionConsumer(sessionId, consumerId, reason);
37
37
  if (!released) {
38
38
  return reply.code(404).send({ error: "Transcode session was not found." });
39
39
  }