@torrent-tv/proxy 2.89.6 → 2.89.7

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 (436) 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 +338 -338
  13. package/CHANGELOG.md +5 -0
  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/diagnostics/sctpstate.gdb +31 -31
  19. package/bin/cli.js +684 -684
  20. package/bin/thread-pool.js +30 -30
  21. package/docs/download-architecture.md +261 -261
  22. package/docs/encode-architecture.md +765 -765
  23. package/docs/encode-run-state.md +96 -96
  24. package/docs/logs.md +97 -97
  25. package/docs/playback-start-forecast.md +17 -2
  26. package/docs/socks5-egress-research.md +114 -114
  27. package/docs/storage-architecture.md +273 -273
  28. package/knip.json +14 -14
  29. package/openspec/changes/adaptive-bitrate/design.md +92 -92
  30. package/openspec/changes/adaptive-bitrate/proposal.md +56 -56
  31. package/openspec/changes/adaptive-bitrate/specs/adaptive-bitrate/spec.md +51 -51
  32. package/openspec/changes/adaptive-bitrate/tasks.md +40 -40
  33. package/openspec/changes/binary-distribution/.openspec.yaml +2 -2
  34. package/openspec/changes/binary-distribution/proposal.md +53 -53
  35. package/openspec/changes/chunked-request-bodies/design.md +81 -81
  36. package/openspec/changes/chunked-request-bodies/proposal.md +53 -53
  37. package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -30
  38. package/openspec/changes/chunked-request-bodies/tasks.md +40 -40
  39. package/openspec/changes/cold-start/design.md +98 -98
  40. package/openspec/changes/cold-start/proposal.md +62 -62
  41. package/openspec/changes/cold-start/specs/cold-start/spec.md +47 -47
  42. package/openspec/changes/cold-start/tasks.md +48 -48
  43. package/openspec/changes/disk-cap/.openspec.yaml +2 -2
  44. package/openspec/changes/disk-cap/proposal.md +37 -37
  45. package/openspec/changes/disk-cap/specs/disk-cap/spec.md +25 -25
  46. package/openspec/changes/disk-cap/tasks.md +19 -19
  47. package/openspec/changes/proxy-observability/.openspec.yaml +2 -2
  48. package/openspec/changes/proxy-observability/design.md +38 -38
  49. package/openspec/changes/proxy-observability/proposal.md +49 -49
  50. package/openspec/changes/proxy-observability/specs/observability/spec.md +33 -33
  51. package/openspec/changes/proxy-observability/tasks.md +21 -21
  52. package/openspec/changes/seek-debounce/design.md +118 -118
  53. package/openspec/changes/seek-debounce/proposal.md +59 -59
  54. package/openspec/changes/seek-debounce/specs/seek-debounce/spec.md +41 -41
  55. package/openspec/changes/seek-debounce/tasks.md +33 -33
  56. package/openspec/changes/subtitle-language/.openspec.yaml +2 -2
  57. package/openspec/changes/subtitle-language/proposal.md +50 -50
  58. package/openspec/changes/subtitle-language/specs/subtitle-language/spec.md +34 -34
  59. package/openspec/changes/subtitle-language/tasks.md +26 -26
  60. package/openspec/changes/track-selection/.openspec.yaml +2 -2
  61. package/openspec/changes/track-selection/design.md +47 -47
  62. package/openspec/changes/track-selection/proposal.md +45 -45
  63. package/openspec/changes/track-selection/specs/track-selection/spec.md +41 -41
  64. package/openspec/changes/track-selection/tasks.md +20 -20
  65. package/openspec/changes/transcode-quality/.openspec.yaml +2 -2
  66. package/openspec/changes/transcode-quality/proposal.md +51 -51
  67. package/openspec/changes/transcode-quality/specs/transcode-quality/spec.md +139 -139
  68. package/openspec/changes/transcode-quality/tasks.md +63 -63
  69. package/openspec/config.yaml +38 -38
  70. package/package.json +1 -1
  71. package/public/.well-known/appspecific/com.chrome.devtools.json +1 -1
  72. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  73. package/research/double-spawn-2026-09-10.md +171 -171
  74. package/research/handover-2026-09-13.md +209 -209
  75. package/research/handover-reader-claims-removal-2026-09-12.md +166 -166
  76. package/research/piece-withdrawn-but-still-claimed-2026-09-12.md +175 -175
  77. package/research/preset-benchmark-size-scaling-2026-08-22.md +55 -55
  78. package/research/priority-map-is-the-truth-2026-09-12.md +225 -225
  79. package/routes/api/client-logs/post.js +86 -86
  80. package/routes/api/delivery-sink/get.js +72 -72
  81. package/routes/api/link-probe/get.js +51 -51
  82. package/routes/api/playback-plan/audio-tracks/post.js +29 -29
  83. package/routes/api/playback-plan/post.js +53 -53
  84. package/routes/api/sources/post.js +36 -36
  85. package/routes/api/sources/stats/get.js +132 -132
  86. package/routes/api/sources/warm/post.js +217 -217
  87. package/routes/api/subtitles/get.js +230 -230
  88. package/routes/api/transcode-sessions/fragment-far/post.js +60 -60
  89. package/routes/api/transcode-sessions/net-report/post.js +138 -138
  90. package/routes/api/transcode-sessions/post.js +178 -178
  91. package/routes/api/transcode-sessions/progress/get.js +27 -27
  92. package/routes/api/transcode-sessions/release/post.js +41 -41
  93. package/routes/api/transcode-sessions/seek/post.js +63 -63
  94. package/routes/health/get.js +13 -13
  95. package/routes/healthz/get.js +13 -13
  96. package/routes/stream/get.js +416 -416
  97. package/routes/transcode/audio-file/get.js +64 -64
  98. package/routes/transcode/audio-warm/get.js +95 -95
  99. package/routes/transcode/session-file/get.js +52 -52
  100. package/routes/transcode/variant-file/get.js +95 -95
  101. package/routes/transcode/variant-warm/get.js +84 -84
  102. package/scripts/render-run-graph.js +173 -173
  103. package/server.js +748 -748
  104. package/services/encode/CoverageMap.js +428 -428
  105. package/services/encode/CushionReport.js +345 -345
  106. package/services/encode/EncodeAdmission.js +376 -376
  107. package/services/encode/EncodeOrchestrator.js +1192 -1192
  108. package/services/encode/EncodePlan.js +1368 -1368
  109. package/services/encode/EncodeRun.js +32 -4
  110. package/services/encode/EncodeRuns.js +19 -7
  111. package/services/encode/Encoder.js +142 -142
  112. package/services/encode/EncoderSelection.js +38 -38
  113. package/services/encode/LocalObservations.js +359 -359
  114. package/services/encode/NvencEncoder.js +50 -50
  115. package/services/encode/OutputTimes.js +579 -579
  116. package/services/encode/QsvEncoder.js +58 -58
  117. package/services/encode/Renditions.js +2283 -2283
  118. package/services/encode/RunClock.js +87 -87
  119. package/services/encode/RunProgress.js +79 -79
  120. package/services/encode/SegmentDemand.js +95 -95
  121. package/services/encode/SoftwareEncoder.js +121 -121
  122. package/services/encode/V4l2m2mEncoder.js +53 -53
  123. package/services/encode/VaapiEncoder.js +66 -66
  124. package/services/encode/args.js +418 -418
  125. package/services/encode/available-share.js +89 -89
  126. package/services/encode/calibration.js +361 -361
  127. package/services/encode/contention.js +128 -128
  128. package/services/encode/decode-cost-fit.js +363 -363
  129. package/services/encode/encode-exit.js +116 -114
  130. package/services/encode/encode-run-state.js +551 -551
  131. package/services/encode/encoder-readings.js +43 -43
  132. package/services/encode/fingerprint.js +322 -322
  133. package/services/encode/host-load.js +174 -174
  134. package/services/encode/index.js +9 -9
  135. package/services/encode/learned-median.js +90 -90
  136. package/services/encode/output/EncodedOutput.js +57 -57
  137. package/services/encode/output/Output.js +131 -131
  138. package/services/encode/output/OutputCatalog.js +414 -414
  139. package/services/encode/output/OutputSpec.js +390 -390
  140. package/services/encode/output/Timeline.js +308 -308
  141. package/services/encode/output/cut-grid.js +107 -107
  142. package/services/encode/output/ladder.js +32 -32
  143. package/services/encode/output/playlists.js +284 -284
  144. package/services/encode/output/rates.js +125 -125
  145. package/services/encode/output-key-format.js +21 -21
  146. package/services/encode/piece-completeness.js +60 -2
  147. package/services/encode/quality/EncodeCost.js +1043 -1043
  148. package/services/encode/quality/HostLoad.js +525 -525
  149. package/services/encode/quality/HostTimings.js +249 -249
  150. package/services/encode/quality/OutputQualityState.js +24 -24
  151. package/services/encode/quality/QualityController.js +758 -758
  152. package/services/encode/quality/QualityOffer.js +416 -416
  153. package/services/encode/quality/drain-threat.js +47 -47
  154. package/services/encode/quality/link-budget.js +337 -337
  155. package/services/encode/quality/output-format.js +319 -319
  156. package/services/encode/quality/serving-output.js +216 -216
  157. package/services/encode/quality/visible-rung.js +57 -57
  158. package/services/encode/run-budget.js +97 -97
  159. package/services/encode/run-command.js +3 -1
  160. package/services/encode/run-costs.js +155 -155
  161. package/services/encode/run-inputs.js +53 -53
  162. package/services/encode/segment-formats/fmp4.js +476 -476
  163. package/services/encode/segment-formats/index.js +1 -0
  164. package/services/encode/segment-formats/init-compat.js +324 -324
  165. package/services/encode/segment-formats/mp4-boxes.js +8 -1
  166. package/services/encode/segment-formats/mpegts.js +134 -134
  167. package/services/encode/start-stop-cost.js +178 -178
  168. package/services/encode/throughput.js +97 -97
  169. package/services/encode/torrent-cost.js +88 -88
  170. package/services/identity/installation-id.js +38 -38
  171. package/services/media/SourceFile.js +298 -298
  172. package/services/media/SubtitleOrchestrator.js +167 -167
  173. package/services/media/container/KeyframeTable.js +272 -272
  174. package/services/media/container/ebml-reader.js +159 -159
  175. package/services/media/ffmpeg-banner.js +260 -260
  176. package/services/media/keyframe-probe.js +157 -157
  177. package/services/media/media-info-probe.js +93 -93
  178. package/services/media/playback-planner.js +931 -931
  179. package/services/media/tracks/AudioTrack.js +143 -143
  180. package/services/media/tracks/ImageSubtitleTrack.js +19 -19
  181. package/services/media/tracks/SubtitleTrack.js +38 -38
  182. package/services/media/tracks/VideoTrack.js +33 -33
  183. package/services/media/tracks/audio-bound.js +233 -233
  184. package/services/media/tracks/index.js +15 -15
  185. package/services/media/tracks/language-detect.js +174 -174
  186. package/services/server/OutputLifecycle.js +418 -418
  187. package/services/server/SegmentServing.js +1152 -1152
  188. package/services/server/ViewerRequests.js +785 -785
  189. package/services/server/WaitLedger.js +142 -142
  190. package/services/server/controllers/PlaybackController.js +40 -40
  191. package/services/server/controllers/SubtitleController.js +109 -109
  192. package/services/server/http-responses.js +60 -60
  193. package/services/server/transcode-session-files.js +325 -325
  194. package/services/server/wire-outputs.js +1029 -1029
  195. package/services/storage/Diagnostics.js +202 -202
  196. package/services/storage/MachineBudget.js +235 -235
  197. package/services/storage/allowance.js +107 -107
  198. package/services/storage/core-dumps.js +106 -106
  199. package/services/storage/files/CompletedFiles.js +391 -391
  200. package/services/storage/files/piece-from-whole-file.js +118 -118
  201. package/services/storage/free.js +71 -71
  202. package/services/storage/keep.js +48 -48
  203. package/services/storage/machine-memory.js +56 -56
  204. package/services/storage/memory-report.js +575 -575
  205. package/services/storage/piece-store/piece-disk-store.js +539 -539
  206. package/services/storage/piece-store/piece-lru.js +495 -495
  207. package/services/storage/returns.js +103 -103
  208. package/services/storage/wire.js +175 -175
  209. package/services/torrent/demand/DemandRegister.js +202 -202
  210. package/services/torrent/demand/Urgency.js +137 -137
  211. package/services/torrent/demand/Window.js +118 -118
  212. package/services/torrent/demand/index.js +8 -8
  213. package/services/torrent/demand/pieces.js +140 -140
  214. package/services/torrent/download/SwarmSelection.js +386 -386
  215. package/services/torrent/download/registry.js +102 -102
  216. package/services/torrent/download/withdraw-claim.js +80 -80
  217. package/services/torrent/files.js +455 -455
  218. package/services/torrent/naming.js +619 -619
  219. package/services/torrent/piece-store-of.js +29 -29
  220. package/services/torrent/supply-margin.js +264 -264
  221. package/services/torrent/worker/background-fill.js +213 -213
  222. package/services/torrent/worker/channel.js +271 -271
  223. package/services/torrent/worker/fastest-wires.js +342 -342
  224. package/services/torrent/worker/handle-state.js +23 -23
  225. package/services/torrent/worker/install-webrtc-shim.js +32 -32
  226. package/services/torrent/worker/piece-reader.js +1078 -1078
  227. package/services/torrent/worker/pool-adapter.js +371 -371
  228. package/services/torrent/worker/protocol.js +184 -184
  229. package/services/torrent/worker/resume-warm.js +107 -107
  230. package/services/torrent/worker/webrtc-shim.js +219 -219
  231. package/services/transport/delivery-probe.js +842 -842
  232. package/services/transport/health-collector.js +53 -53
  233. package/services/transport/nat-classifier.js +231 -231
  234. package/services/transport/packet-witness.js +808 -808
  235. package/services/transport/port-mapper.js +235 -235
  236. package/services/transport/registry-api.js +81 -81
  237. package/services/transport/tunnel-client.js +447 -447
  238. package/services/transport/usrsctp-state.js +175 -175
  239. package/services/transport/webrtc-manager.js +484 -484
  240. package/services/viewer/Assignments.js +340 -340
  241. package/services/viewer/PriorityOrchestrator.js +325 -325
  242. package/services/viewer/Viewer.js +691 -691
  243. package/services/viewer/Viewers.js +368 -368
  244. package/services/viewer/active-output.js +37 -37
  245. package/services/viewer/audio-start.js +46 -46
  246. package/services/viewer/buffer-trend.js +81 -81
  247. package/services/viewer/choices.js +647 -647
  248. package/services/viewer/media-time.js +355 -355
  249. package/services/viewer/playback-readiness.js +635 -635
  250. package/services/viewer/positions.js +126 -126
  251. package/services/viewer/report-intake.js +46 -46
  252. package/store/source-registry.js +71 -71
  253. package/test/asset-paths.test.js +28 -28
  254. package/test/audio-buffer-continuity.test.js +77 -77
  255. package/test/audio-inventory.test.js +212 -212
  256. package/test/audio-track-bitrate.test.js +40 -40
  257. package/test/available-share.test.js +76 -76
  258. package/test/background-fill.test.js +190 -190
  259. package/test/client-log-file.test.js +110 -110
  260. package/test/completed-files.test.js +115 -115
  261. package/test/concurrent-cost.test.js +148 -148
  262. package/test/container-media-info.test.js +228 -228
  263. package/test/contention.test.js +76 -76
  264. package/test/core-dumps.test.js +57 -57
  265. package/test/coverage-follows-the-disk.test.js +228 -228
  266. package/test/coverage-map.test.js +195 -195
  267. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  268. package/test/cut-times-timeline.test.js +65 -65
  269. package/test/cuts-follow-published-grid.test.js +109 -109
  270. package/test/data-channel-frame.test.js +63 -63
  271. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  272. package/test/dead-torrent-handle.test.js +52 -52
  273. package/test/declared-rates.test.js +116 -116
  274. package/test/declared-tracks.test.js +43 -43
  275. package/test/decode-cost-fit.test.js +202 -202
  276. package/test/delivery-probe.test.js +393 -393
  277. package/test/demand-register.test.js +206 -206
  278. package/test/dht-bootstrap.test.js +72 -72
  279. package/test/drain-threat.test.js +65 -65
  280. package/test/duplicate-add.test.js +48 -48
  281. package/test/encode-admission.test.js +146 -146
  282. package/test/encode-cost.test.js +275 -275
  283. package/test/encode-exit.test.js +111 -111
  284. package/test/encode-orchestrator.test.js +426 -426
  285. package/test/encode-plan-viewers.test.js +725 -725
  286. package/test/encode-plan.test.js +545 -545
  287. package/test/encode-run-state.test.js +314 -314
  288. package/test/encode-run.test.js +38 -0
  289. package/test/encode-slope.test.js +46 -46
  290. package/test/encoded-output.test.js +39 -39
  291. package/test/encoder-kinds.test.js +122 -122
  292. package/test/encoder-readings.test.js +68 -68
  293. package/test/every-claimant-is-told-its-share.test.js +152 -152
  294. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  295. package/test/failed-start-breaker.test.js +202 -202
  296. package/test/fastest-wires.test.js +143 -143
  297. package/test/ffmpeg-stream-counts.test.js +78 -78
  298. package/test/file-edges.test.js +191 -191
  299. package/test/fixtures/refused-audio-20261002.json +10 -0
  300. package/test/fmp4-presentation-clock.test.js +4 -2
  301. package/test/fmp4-self-contained.test.js +80 -80
  302. package/test/fmp4-timestamps.test.js +140 -140
  303. package/test/fmp4-track-completeness.test.js +41 -41
  304. package/test/health-metrics.test.js +38 -38
  305. package/test/held-request-width.test.js +157 -157
  306. package/test/helpers/encode-run.js +240 -240
  307. package/test/helpers/output-spec.js +63 -63
  308. package/test/host-load.test.js +68 -68
  309. package/test/index-accuracy-is-about-the-file.test.js +128 -128
  310. package/test/init-compat.test.js +219 -219
  311. package/test/input-lost-quiets-the-plan.test.js +261 -261
  312. package/test/input-unavailable.test.js +48 -48
  313. package/test/installation-id.test.js +39 -39
  314. package/test/keeping-period.test.js +83 -83
  315. package/test/keyframe-index-accuracy.test.js +188 -188
  316. package/test/keyframes-belong-to-the-file.test.js +249 -249
  317. package/test/learned-median.test.js +37 -37
  318. package/test/letting-go-asks-who-is-watching.test.js +191 -191
  319. package/test/limit-row-by-area.test.js +60 -60
  320. package/test/link-budget.test.js +111 -111
  321. package/test/link-probe.test.js +56 -56
  322. package/test/local-encoding-data.test.js +273 -273
  323. package/test/logger-repeats.test.js +134 -134
  324. package/test/look-ahead-coverage.test.js +56 -56
  325. package/test/manager-surface.test.js +291 -291
  326. package/test/matroska-cues-track.test.js +192 -192
  327. package/test/media-time.test.js +62 -62
  328. package/test/memory-budget.test.js +390 -390
  329. package/test/move-cost.test.js +216 -216
  330. package/test/mp4-subtitles.test.js +173 -173
  331. package/test/one-authority.test.js +285 -285
  332. package/test/one-budget.test.js +149 -149
  333. package/test/one-resource-divided.test.js +185 -185
  334. package/test/one-serving-output-per-height.test.js +458 -458
  335. package/test/orchestrator-wired.test.js +207 -207
  336. package/test/output-catalog.test.js +39 -39
  337. package/test/output-shape.test.js +21 -21
  338. package/test/output-spec.test.js +251 -251
  339. package/test/output-speed.test.js +87 -87
  340. package/test/outputs-being-prepared.test.js +40 -40
  341. package/test/packet-witness-ring.test.js +236 -236
  342. package/test/packet-witness.test.js +148 -148
  343. package/test/piece-completeness.test.js +37 -1
  344. package/test/piece-disk-store.test.js +401 -401
  345. package/test/piece-from-whole-file.test.js +129 -129
  346. package/test/piece-lru.test.js +319 -319
  347. package/test/piece-reader.test.js +162 -162
  348. package/test/piece-selection-offset.test.js +85 -85
  349. package/test/piece-store-eviction.test.js +595 -595
  350. package/test/piece-store-never-refuses.test.js +153 -153
  351. package/test/piece-store-reservations.test.js +403 -403
  352. package/test/piece-store-slow-disk.test.js +159 -159
  353. package/test/piece-tail.test.js +97 -97
  354. package/test/plan-host-timings.test.js +68 -68
  355. package/test/plan-is-steady.test.js +225 -225
  356. package/test/playback-readiness.test.js +518 -518
  357. package/test/playback-start-regressions.test.js +101 -101
  358. package/test/priority-map-download.test.js +174 -174
  359. package/test/priority-map-emptied.test.js +204 -204
  360. package/test/priority-map-per-output.test.js +215 -215
  361. package/test/priority-map.test.js +163 -163
  362. package/test/probe-wedge-certainty.test.js +60 -60
  363. package/test/produced-copy-choice.test.js +213 -213
  364. package/test/published-timeline.test.js +83 -83
  365. package/test/quality-offer.test.js +160 -160
  366. package/test/rate-control-in-the-output.test.js +180 -180
  367. package/test/read-survives-withdrawal.test.js +164 -164
  368. package/test/read-window.test.js +365 -365
  369. package/test/resume-warm.test.js +39 -39
  370. package/test/run-graph-drift.test.js +37 -37
  371. package/test/run-inputs.test.js +80 -80
  372. package/test/run-intervals.test.js +100 -100
  373. package/test/run-position-follows-published-grid.test.js +89 -89
  374. package/test/run-progress.test.js +64 -64
  375. package/test/same-height-switch.test.js +663 -663
  376. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  377. package/test/seek-landing.test.js +109 -109
  378. package/test/seek-target-not-superseded.test.js +195 -195
  379. package/test/segment-cut-times.test.js +63 -63
  380. package/test/segment-demand.test.js +80 -80
  381. package/test/segment-hold-supersede.test.js +91 -91
  382. package/test/segment-store-eviction.test.js +247 -247
  383. package/test/segment-store.test.js +352 -352
  384. package/test/segment-true-start.test.js +86 -86
  385. package/test/segments-are-shared.test.js +176 -176
  386. package/test/send-chunk-bytes.test.js +86 -86
  387. package/test/serving-output.test.js +102 -102
  388. package/test/shared-piece-store.test.js +310 -310
  389. package/test/sidecar-naming.test.js +142 -142
  390. package/test/soundtrack-rate-bound.test.js +289 -289
  391. package/test/source-file.test.js +133 -133
  392. package/test/source-registry.test.js +18 -18
  393. package/test/split-a-stretch.test.js +139 -139
  394. package/test/stale-request-after-seek.test.js +158 -158
  395. package/test/startup-readings.test.js +124 -124
  396. package/test/stream-route.test.js +237 -237
  397. package/test/subtitle-cue-framing.test.js +200 -200
  398. package/test/subtitle-cue-source.test.js +102 -102
  399. package/test/subtitle-cursor.test.js +63 -63
  400. package/test/subtitle-defaults.test.js +118 -118
  401. package/test/subtitle-language.test.js +252 -252
  402. package/test/supply-margin.test.js +190 -190
  403. package/test/swarm-follows-readers.test.js +174 -174
  404. package/test/swarm-reach.test.js +130 -130
  405. package/test/swarm-selection.test.js +220 -220
  406. package/test/tail-duplication.test.js +167 -167
  407. package/test/the-channel-has-both-ends.test.js +91 -91
  408. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  409. package/test/thread-pool.test.js +53 -53
  410. package/test/timeline.test.js +84 -84
  411. package/test/torrent-contents.test.js +235 -235
  412. package/test/torrent-cost.test.js +71 -71
  413. package/test/torrent-files.test.js +221 -221
  414. package/test/torrent-naming.test.js +255 -255
  415. package/test/tracks-begin-together.test.js +209 -209
  416. package/test/tunnel-renewal.test.js +167 -167
  417. package/test/upload-hurry.test.js +186 -186
  418. package/test/usrsctp-state.test.js +131 -131
  419. package/test/video-facts.test.js +102 -102
  420. package/test/viewer-assignments.test.js +143 -143
  421. package/test/viewer-outputs.test.js +285 -285
  422. package/test/viewer-presence.test.js +116 -116
  423. package/test/viewer-states.test.js +189 -189
  424. package/test/viewer-subtitle-subscription.test.js +96 -96
  425. package/test/viewer.test.js +139 -139
  426. package/test/visible-rung.test.js +37 -37
  427. package/test/wait-ledger.test.js +100 -100
  428. package/test/webrtc-shim.test.js +149 -149
  429. package/test/wedge-certainty.test.js +131 -131
  430. package/test/withdraw-piece-claim.test.js +212 -212
  431. package/test/worker-channel.test.js +158 -158
  432. package/utils/client-log-file.js +151 -151
  433. package/utils/logger.js +312 -312
  434. package/utils/parse-range.js +25 -25
  435. package/utils/perf.js +59 -59
  436. package/utils/torrent-source-key.js +38 -38
@@ -1,1029 +1,1029 @@
1
- /**
2
- * @file Wiring of the outputs, the viewers and the encoding.
3
- *
4
- * Builds each component and hands it the narrow host it reads, and nothing
5
- * else. It holds no behaviour: every member that used to be a method of the
6
- * session manager is a method of the component that owns it now. What it
7
- * returns is the set of components and the settings they share, for
8
- * `server.js` to give each route the ones that route asks.
9
- */
10
-
11
- import { logger } from "../../utils/logger.js";
12
- import { KeyframeTables } from "../media/KeyframeTables.js";
13
- import { waits } from "./WaitLedger.js";
14
- import { readMachineState, readProcessCpuSeconds, readProxyCpuSeconds, readSystemCpu, shareOfMachine } from "../encode/host-load.js";
15
- import { minimumBufferFrom } from "../torrent/supply-margin.js";
16
- import { PriorityOrchestrator } from "../viewer/PriorityOrchestrator.js";
17
- import { softwareDescriptor } from "../encode/hwaccel.js";
18
- import { resolveSegmentFormat } from "../encode/segment-formats/index.js";
19
- import { Timelines } from "../encode/output/Timeline.js";
20
- import { SourceFiles } from "../media/SourceFile.js";
21
- import { SegmentStore } from "../storage/segment-store/SegmentStore.js";
22
- import { EncodeCost } from "../encode/quality/EncodeCost.js";
23
- import { QualityOffer } from "../encode/quality/QualityOffer.js";
24
- import { activeOutputFor } from "../viewer/active-output.js";
25
- import {
26
- acceptsGeneration,
27
- askQualityOf,
28
- audioBeingWarmedOf,
29
- audioChoiceOf,
30
- chooseAudioTrack,
31
- chooseOutput,
32
- chosenOutputOf,
33
- consumersOn,
34
- dropAskOf,
35
- generationOfRequest,
36
- givenOutputOf,
37
- heightsChosenAs,
38
- highestGivenSegmentOf,
39
- holdForResponse,
40
- linkMbpsOf,
41
- linkReportOf,
42
- bufferOf,
43
- bufferedSecondsOf,
44
- visiblePictureOf,
45
- linkReportsOn,
46
- noteAudioBeingWarmed,
47
- noteGivenOutput,
48
- noteSameHeightSwitch,
49
- noteServingVerdict,
50
- noteStepBeingWarmed,
51
- noteStepOnScreen,
52
- outputsBeingPrepared,
53
- placeOn,
54
- presentOn,
55
- qualityModeOf,
56
- sameHeightSwitchOf,
57
- servingVerdictOf,
58
- standingAskOf,
59
- stepBeingWarmedOf,
60
- stepBeingWarmedSinceOf,
61
- stepOnScreenOf,
62
- switchingOnto,
63
- watches
64
- } from "../viewer/choices.js";
65
- import { viewerSecondsOn, viewerSegmentsOn } from "../viewer/positions.js";
66
- import { Viewers } from "../viewer/Viewers.js";
67
- import { OutputCatalog } from "../encode/output/OutputCatalog.js";
68
- import { ViewerRequests } from "./ViewerRequests.js";
69
- import { OutputLifecycle } from "./OutputLifecycle.js";
70
- import { SegmentServing } from "./SegmentServing.js";
71
- import { audioStartSecondsFor } from "../viewer/audio-start.js";
72
- import { forecastRate, predictPlaybackReadiness, RateTrend } from "../viewer/playback-readiness.js";
73
- import { audioRenditionName } from "../media/audio-inventory.js";
74
- import { Renditions } from "../encode/Renditions.js";
75
- import { CushionReport, LOOKAHEAD_PAUSE_SECONDS } from "../encode/CushionReport.js";
76
- import { EncodeRuns } from "../encode/EncodeRuns.js";
77
- import { OutputTimes } from "../encode/OutputTimes.js";
78
- import { HostLoad } from "../encode/quality/HostLoad.js";
79
- import { HostTimings } from "../encode/quality/HostTimings.js";
80
- import { BUDGET_CHECK_INTERVAL_MS, QualityController } from "../encode/quality/QualityController.js";
81
- import { EncodeOrchestrator } from "../encode/EncodeOrchestrator.js";
82
- import { EncodeAdmission } from "../encode/EncodeAdmission.js";
83
- import { EncoderSelection } from "../encode/EncoderSelection.js";
84
- import { OutputOpening } from "../encode/OutputOpening.js";
85
- import { segmentFormatOfKey } from "../encode/output-key-format.js";
86
- import { OutputSpec } from "../encode/output/OutputSpec.js";
87
- import { compareInits } from "../encode/segment-formats/init-compat.js";
88
- import { nominalKbpsFor, AUDIO_TRANSCODE_KBPS } from "../encode/args.js";
89
- import { audioReadingFor } from "../encode/audio-work-rate.js";
90
- import { probeInputMediaInfo } from "../media/media-info-probe.js";
91
- import { probeVideoKeyframeTimes } from "../media/keyframe-probe.js";
92
- import { wireMachineBudget } from "../storage/wire.js";
93
- import { Returns } from "../storage/returns.js";
94
- import { freeBytesFor } from "../storage/free.js";
95
- import path from "node:path";
96
- import { contentOf, LocalObservations } from "../encode/LocalObservations.js";
97
- import { configurationKeyOf } from "../encode/fingerprint.js";
98
- import { PROXY_ROOT } from "../encode/quality/HostTimings.js";
99
- import { qualityStateOf } from "../encode/quality/OutputQualityState.js";
100
-
101
- // Where a variant and an audio rendition live under a session — `v/<height>/…`
102
- // and `a/<track>/…` — is stated in `encode/output/playlists.js`, beside the lines that
103
- // write those addresses into a master playlist. The routes that parse them back
104
- // are in `server.js`.
105
-
106
- const CLEANUP_INTERVAL_MS = 30_000;
107
- const DEFAULT_SEGMENT_DURATION_SEC = 4;
108
- // Idle TTL: a session is disposed this long after the last segment/playlist
109
- // access. Long enough that a viewer who pauses, backgrounds the tab, or briefly
110
- // turns the phone off can resume WITHOUT a cold ffmpeg restart (the warm session
111
- // also backs the seamless auto-reconnect). ffmpeg stops producing at the
112
- // look-ahead cap when idle, so a lingering session costs retained segments on
113
- // disk, not sustained CPU. Active playback refreshes the timer on every segment
114
- // fetch, so it never expires mid-watch.
115
- // How long a session outlives the BROWSER, not the viewing. Since server
116
- // 0.8.103 a browser that holds a session re-asserts it every 30 s, so an open
117
- // tab never consumes this at all — not while paused, not across a three-hour
118
- // film. What is left is the case where the browser has genuinely gone: the tab
119
- // was killed without releasing, the phone slept, the network dropped. Keeping
120
- // the session means such a viewer comes back to a warm encoder instead of
121
- // waiting out a cold start; the cost while nobody is there is disk for the
122
- // produced segments, since the encoder is suspended and burns no CPU, and that
123
- // disk is already bounded by the pool's 10 GB cap with eviction. Thirty minutes
124
- // covers a meal, a phone call or a lift ride.
125
- const DEFAULT_SESSION_TTL_MS = 30 * 60 * 1000;
126
- const DEFAULT_STARTUP_WAIT_MS = 5_000;
127
-
128
- /**
129
- * Convert a bind-all host address to the loopback address so that
130
- * the HLS input URL is always reachable from the same machine.
131
- *
132
- * @param {string} host
133
- * @returns {string}
134
- */
135
- function toLoopbackHost(host) {
136
- if (host === "0.0.0.0" || host === "::") {
137
- return "127.0.0.1";
138
- }
139
- return host;
140
- }
141
-
142
- /**
143
- * Build the HTTP base URL (scheme + host + port) for the local proxy server.
144
- *
145
- * @param {string} host - Bind host (may be "0.0.0.0" or "::").
146
- * @param {number} port
147
- * @returns {string} e.g. "http://127.0.0.1:9090"
148
- */
149
- function buildHttpBaseUrl(host, port) {
150
- const url = new URL("http://localhost");
151
- url.hostname = toLoopbackHost(host);
152
- url.port = String(port);
153
- return url.origin;
154
- }
155
-
156
- /**
157
- * @typedef {Object} WireOutputsOptions
158
- * @property {boolean} enabled - Whether HLS transcoding is enabled.
159
- * @property {string} ffmpegBin - Path to the ffmpeg executable.
160
- * @property {string} localBindHost - Host the proxy HTTP server is bound to.
161
- * @property {number} localPort - Port the proxy HTTP server is listening on.
162
- * @property {number} [segmentDurationSec] - HLS segment length in seconds.
163
- * @property {number} [sessionTtlMs] - Session idle TTL in milliseconds.
164
- * @property {number} [startupWaitMs] - Max time to wait for the first playlist file.
165
- * @property {string} [segmentFormatId] - Output container: "fmp4" (default)
166
- * or "mpegts". See `../segment-formats/index.js`.
167
- */
168
-
169
- /**
170
- * @typedef {Object} HlsSession
171
- * @property {string} id - The name of the output it produces.
172
- * @property {string} fileName - Display name of the file being transcoded.
173
- * @property {import("../media/container/KeyframeTable.js").KeyframeTable} keyframes -
174
- * Where this file's keyframes are. One object per file, held by every session
175
- * of it, so a table read late still reaches them. Used to snap a source seek
176
- * onto a known-valid position (see #startEncodeRun).
177
- */
178
-
179
- /**
180
- * Build the components and connect them.
181
- *
182
- * @param {WireOutputsOptions} options
183
- * @returns {object} The components, and the settings they read.
184
- */
185
- export function wireOutputs({
186
- enabled,
187
- ffmpegBin,
188
- localBindHost,
189
- localPort,
190
- segmentDurationSec = DEFAULT_SEGMENT_DURATION_SEC,
191
- sessionTtlMs = DEFAULT_SESSION_TTL_MS,
192
- startupWaitMs = DEFAULT_STARTUP_WAIT_MS,
193
- // Where every file's keyframe table lives, and the only thing that reads
194
- // one. A session asks for its file's table and is handed the object every
195
- // other reader of that file holds, so a table that arrives late reaches the
196
- // sessions created before it. Built here when nothing supplied one, which
197
- // is a registry with no reader: it answers "not read" about every file, and
198
- // every picture is then re-encoded — the correct behaviour for a proxy
199
- // wired without a container reader, and what every unit test gets.
200
- keyframeTables = new KeyframeTables(),
201
- videoEncoder = null,
202
- softwarePresetBenchmark = null,
203
- // What every encoder this host may use was qualified and measured to do at
204
- // startup, by kind (`encode/calibration.js`). Takes the place of the one
205
- // array above, which a test may still hand in on its own.
206
- calibration = null,
207
- decodeCostModel = null,
208
- getSourceStats = null,
209
- setPriorityMap = null,
210
- // What a second job costs on this host, measured at startup. Null when it
211
- // could not be measured, and then nothing is corrected — the alternative
212
- // is inventing a penalty, which is the same fault as inventing a fill rate.
213
- contentionPenalties = null,
214
- copySpeedX = null,
215
- audioCalibration = [],
216
- tonemapSupported = false,
217
- getCachedMediaInfo = null,
218
- getCachedAudioTracks = null,
219
- getContainerMediaInfo = null,
220
- fetchWholeFile = null,
221
- segmentFormatId = undefined,
222
- stateDir = "",
223
- segmentStore = null,
224
- getTorrentTotals,
225
- startStopCost = null,
226
- spillDisk = null,
227
- wholeFiles = null,
228
- diagnostics = null,
229
- diagnosticsRoot = "",
230
- memoryClaimant = null,
231
- budgetPolicy = null}) {
232
- const parts = {};
233
- const audioDescriptionOf = (output) => (getCachedAudioTracks?.({
234
- sourceKey: output.file.sourceKey, fileIndex: output.spec.grid?.fileIndex ?? output.file.fileIndex
235
- }) ?? []).find((track) => track.fileIndex === output.spec.audio?.fileIndex &&
236
- track.sourceTrackIndex === output.spec.audio?.trackIndex) ?? null;
237
- // Encode components receive only the storage operations they use. The
238
- // concrete SegmentStore remains owned by this assembly and is never handed
239
- // to the encode layer.
240
- const segmentCoverage = {
241
- provenNumbers: (address) => parts.segmentStore.provenNumbers(address),
242
- announce: (address, index) => parts.segmentStore.announce(address, index),
243
- filesHeld: (address) => parts.segmentStore.filesHeld(address),
244
- clearUpAfter: (address, startedAt) => parts.segmentStore.clearUpAfter(address, startedAt)
245
- };
246
- const segmentFiles = {
247
- pathFor: (address) => parts.segmentStore.pathFor(address),
248
- initOf: (address) => parts.segmentStore.initOf(address),
249
- directoryFor: (address) => parts.segmentStore.directoryFor(address),
250
- publish: (address, makingName, format, read) => parts.segmentStore.publish(address, makingName, format, read),
251
- closedBytesOf: (address, makingName) => parts.segmentStore.closedBytesOf(address, makingName),
252
- mediaRangesOf: (address, index, where) => parts.segmentStore.mediaRangesOf(address, index, where),
253
- remove: (address, index, because) => parts.segmentStore.remove(address, index, because)
254
- };
255
- const segmentOutputFiles = {
256
- addresses: () => parts.segmentStore.addresses(),
257
- isClosed: (address, index) => parts.segmentStore.isClosed(address, index),
258
- lastReadAt: (address) => parts.segmentStore.lastReadAt(address),
259
- directoryFor: (address) => parts.segmentStore.directoryFor(address),
260
- useFormat: (address, format) => parts.segmentStore.useFormat(address, format)
261
- };
262
- const segmentPaths = {
263
- pathOf: (address, index) => parts.segmentStore.pathOf(address, index),
264
- sizesOf: (address) => parts.segmentStore.sizesOf(address)
265
- };
266
- /**
267
- * Whether everything this output will ever serve is made: every segment of
268
- * its timeline closed in the store. Such an output needs no encoder and
269
- * holds no place, however many watch it.
270
- *
271
- * @param {object} session
272
- * @returns {boolean}
273
- */
274
- const finishedOutput = (session) => {
275
- const count = Number(session?.timeline?.segmentCount) || 0;
276
- return count > 0 && parts.segmentStore.provenNumbers(session.outputKey).length >= count;
277
- };
278
- // The nominal limits a size may be produced at, highest first. ONE list, read
279
- // by the opening of an output and by the move between limits of a height, so
280
- // the two cannot disagree about which limits exist. Only the size's own until
281
- // a set of lower limits is decided (roadmap item 97, step 14): a lower limit
282
- // handed to a viewer must come with the page saying so. Asked with the whole
283
- // frame, because the row is chosen by area (`limitRowFor`).
284
- parts.limitsFor = (frame) => [nominalKbpsFor(frame)];
285
- // What the torrent and the proxy itself spend on this host, and how fast each watched torrent moves.
286
- parts.hostLoad = new HostLoad({
287
- readMachineState,
288
- readProcessCpuSeconds,
289
- readProxyCpuSeconds,
290
- readSystemCpu,
291
- shareOfMachine,
292
- liveRunsOf: (...args) => parts.encodeRuns.liveRunsOf(...args),
293
- runStateOf: (...args) => parts.encodeRuns.runStateOf(...args),
294
- get getSourceStats() { return parts.getSourceStats; },
295
- get getTorrentTotals() { return parts.getTorrentTotals; },
296
- get outputs() { return parts.outputs; },
297
- });
298
- // Where each segment of an output begins, and how that table is corrected from what the encoder produced.
299
- parts.outputTimes = new OutputTimes({
300
- logger,
301
- runsOf: (...args) => parts.encodeRuns.runsOf(...args),
302
- stopEncodeRun: (...args) => parts.encodeRuns.stopEncodeRun(...args),
303
- planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
304
- get outputs() { return parts.outputs; },
305
- get segmentDurationSec() { return parts.segmentDurationSec; },
306
- });
307
- // The encoders of this proxy: built where the plan places them, followed while they run, accounted when they end.
308
- parts.encodeRuns = new EncodeRuns({
309
- logger,
310
- // What this host is doing with an encode is learned each time a run has
311
- // measured its processing speed, on every host.
312
- noteRunSpeedMeasured: (session, run) => {
313
- void parts.encodeCost.learnFrom(session, run);
314
- },
315
- // What an admitted encode was seen to do, filed under its configuration.
316
- observeEncodeEnded: (session) => {
317
- if (!parts.localObservations || !session?.spec?.video?.encode) {
318
- return;
319
- }
320
- const alone = Number(qualityStateOf(session).lastAloneSpeed);
321
- parts.localObservations.noteEncode({
322
- spec: session.spec,
323
- content: contentOf(session.file),
324
- aloneSpeedX: Number.isFinite(alone) && alone > 0 ? alone : null,
325
- segmentKbps: segmentRatesOf(session)
326
- });
327
- },
328
- viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
329
- inputOf: (...args) => parts.renditions.inputOf(...args),
330
- producedNumbers: (...args) => parts.serving.producedNumbers(...args),
331
- servesAudioSeparately: (...args) => parts.renditions.servesAudioSeparately(...args),
332
- disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
333
- get contentionPenalties() { return parts.contentionPenalties; },
334
- get encodeCost() { return parts.encodeCost; },
335
- get encodeOrchestrator() { return parts.encodeOrchestrator; },
336
- get ffmpegBin() { return parts.ffmpegBin; },
337
- get outputTimes() { return parts.outputTimes; },
338
- get outputs() { return parts.outputs; },
339
- get priority() { return parts.priority; },
340
- get segmentDurationSec() { return parts.segmentDurationSec; },
341
- segmentFiles,
342
- get videoEncoder() { return parts.encoders.current; },
343
- get encoders() { return parts.encoders; },
344
- invalidateWaits: (output) => parts.serving.invalidateWaits(output),
345
- productionFailed: (output) => parts.renditions.noteProductionFailed(output),
346
- });
347
- // How much film is ready in front of the viewers, said; and the spare soundtracks fetched once it is full.
348
- parts.cushion = new CushionReport({
349
- viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
350
- linkReportsOn: (output) => linkReportsOn(parts.viewers, output),
351
- SourceFiles,
352
- logger,
353
- producedNumbers: (...args) => parts.serving.producedNumbers(...args),
354
- get encodeRuns() { return parts.encodeRuns; },
355
- get fetchWholeFile() { return parts.fetchWholeFile; },
356
- get getCachedAudioTracks() { return parts.getCachedAudioTracks; },
357
- get hostLoad() { return parts.hostLoad; },
358
- get lookaheadSeconds() { return parts.lookaheadSeconds; },
359
- get outputTimes() { return parts.outputTimes; },
360
- get outputs() { return parts.outputs; },
361
- });
362
- // The steps of a picture and its soundtracks: which output answers each, made when first asked for, and the master playlist listing them.
363
- // The cushion this file needs, from its segment length and the worst
364
- // interruption its supply has shown — one statement read by every operation
365
- // that asks it.
366
- const minimumBufferSecondsOf = (output) => minimumBufferFrom({
367
- segmentSeconds: parts.segmentDurationSec,
368
- worstSupplyWaitSec: parts.hostLoad.supplyFor(output.file)?.worstWaitSec
369
- })?.seconds ?? null;
370
- parts.renditions = new Renditions({
371
- // Whether this proxy re-encodes at all: a soundtrack with no stated rate is
372
- // re-encoded where it may be, and copied where it may not.
373
- get transcodeEnabled() { return parts.enabled; },
374
- observedPeakMbps: (spec) => parts.localObservations?.peakMbps(spec) ?? null,
375
- // A viewer has been moved onto an output prepared for them: how long it
376
- // took, and what they held.
377
- notePreparation: (output, seconds, bufferedSec) =>
378
- parts.localObservations?.notePreparation({ spec: output?.spec, seconds, bufferedSec }),
379
- viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
380
- audioStartSecondsFor: (args) => audioStartSecondsFor({ ...args, viewers: parts.viewers }),
381
- activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
382
- // WHAT ENCODING IS TOLD ABOUT A PERSON, and what it may tell the viewer
383
- // layer about them: values and names, never the viewer itself. Steps and
384
- // soundtracks are chosen, warmed and left per person, so this is the widest
385
- // of the three sets — and every one of them is a call on the owner, which
386
- // is what keeps one writer per fact.
387
- viewerCountOn: (output) => parts.viewers.forOutput(output).size,
388
- // Whether anything still stands on it — somebody watching, or an
389
- // assignment not yet released. See `Viewers.stillNeeded`.
390
- outputStillNeeded: (output) => parts.viewers.stillNeeded(output),
391
- consumersOn: (output) => consumersOn(parts.viewers, output),
392
- presentOn: (output) => presentOn(parts.viewers, output),
393
- qualityModeOf: (output, consumerId) => qualityModeOf(parts.viewers, output, consumerId),
394
- linkMbpsOf: (output, consumerId) => linkMbpsOf(parts.viewers, output, consumerId),
395
- audioChoiceOf: (output, consumerId) => audioChoiceOf(parts.viewers, output, consumerId),
396
- chooseAudioTrack: (output, consumerId, choice) =>
397
- chooseAudioTrack(parts.viewers, output, consumerId, choice),
398
- stepOnScreenOf: (output, consumerId) => stepOnScreenOf(parts.viewers, output, consumerId),
399
- noteStepOnScreen: (output, consumerId, stepId) =>
400
- noteStepOnScreen(parts.viewers, output, consumerId, stepId),
401
- stepBeingWarmedOf: (output, consumerId) => stepBeingWarmedOf(parts.viewers, output, consumerId),
402
- stepBeingWarmedSinceOf: (output, consumerId) => stepBeingWarmedSinceOf(parts.viewers, output, consumerId),
403
- noteStepBeingWarmed: (output, consumerId, stepId) =>
404
- noteStepBeingWarmed(parts.viewers, output, consumerId, stepId),
405
- audioBeingWarmedOf: (output, consumerId) => audioBeingWarmedOf(parts.viewers, output, consumerId),
406
- noteAudioBeingWarmed: (output, consumerId, renditionId) =>
407
- noteAudioBeingWarmed(parts.viewers, output, consumerId, renditionId),
408
- watches: (output, consumerId) => watches(parts.viewers, output, consumerId),
409
- placeOn: (output, consumerId, seconds) => placeOn(parts.viewers, output, consumerId, seconds),
410
- // A viewer's own assignments: which output answered a height and segment in
411
- // one generation of their viewing, so a repeat is answered the same way.
412
- // Values in and out, like everything above.
413
- generationOfRequest: (consumerId, stated) => generationOfRequest(parts.viewers, consumerId, stated),
414
- givenOutputOf: (consumerId, generation, askedHeight, segmentIndex) =>
415
- givenOutputOf(parts.viewers, consumerId, generation, askedHeight, segmentIndex),
416
- noteGivenOutput: (consumerId, generation, askedHeight, segmentIndex, outputKey) =>
417
- noteGivenOutput(parts.viewers, consumerId, generation, askedHeight, segmentIndex, outputKey),
418
- // The output this viewer was chosen at a height, and the rule's choice of
419
- // it — the viewer's own record, never one per file.
420
- chosenOutputOf: (consumerId, askedHeight) => chosenOutputOf(parts.viewers, consumerId, askedHeight),
421
- chooseOutput: (consumerId, askedHeight, outputKey) => chooseOutput(parts.viewers, consumerId, askedHeight, outputKey),
422
- noteServingVerdict: (consumerId, verdict) => noteServingVerdict(parts.viewers, consumerId, verdict),
423
- // A move between two limits of the height on a viewer's screen (roadmap
424
- // item 97, step 12): which heights their choice is the output on screen
425
- // under, the segment they were last given, the move being prepared, and
426
- // whether a segment is closed on the output being prepared.
427
- limitsFor: (frame) => parts.limitsFor(frame),
428
- heightsChosenAs: (consumerId, outputKey) => heightsChosenAs(parts.viewers, consumerId, outputKey),
429
- highestGivenSegmentOf: (consumerId, askedHeight) => highestGivenSegmentOf(parts.viewers, consumerId, askedHeight),
430
- sameHeightSwitchOf: (consumerId) => sameHeightSwitchOf(parts.viewers, consumerId),
431
- noteSameHeightSwitch: (consumerId, value) => noteSameHeightSwitch(parts.viewers, consumerId, value),
432
- switchingOnto: (output) => switchingOnto(parts.viewers, output),
433
- // What a viewer holds, and the cushion this file needs before a move that
434
- // is not urgent is made (roadmap item 98).
435
- bufferedSecondsOf: (consumerId) => bufferedSecondsOf(parts.viewers, consumerId),
436
- minimumBufferSecondsFor: (output) => minimumBufferSecondsOf(output),
437
- // Whether the whole machine has a place for one more encoder on this output,
438
- // asked before a preparation is recorded.
439
- admitsPreparation: (output) => parts.admission.admitsPreparation(output?.outputKey ?? ""),
440
- segmentClosed: (key, index) => parts.segmentStore.isClosed(key, index),
441
- // What a gone output left in the store, and whether another output's header
442
- // may stand in for its own.
443
- storedPieceReady: (key, fileName) => parts.serving.hasStoredPiece(key, fileName),
444
- headersCompatible: (goneKey, liveKey) => parts.serving.headersCompatible(goneKey, liveKey),
445
- placeViewerOn: (...args) => parts.viewerRequests.placeViewerOn(...args),
446
- audioRenditionName,
447
- logger,
448
- viewerLeaves: (...args) => parts.lifecycle.viewerLeaves(...args),
449
- createOrGetSession: (...args) => parts.viewerRequests.createOrGetSession(...args),
450
- planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
451
- disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
452
- viewerPositionOf: (...args) => parts.viewerRequests.viewerPositionOf(...args),
453
- get encodeRuns() { return parts.encodeRuns; },
454
- get fileStartTimeReads() { return parts.fileStartTimeReads; },
455
- set fileStartTimeReads(value) { parts.fileStartTimeReads = value; },
456
- get getCachedAudioTracks() { return parts.getCachedAudioTracks; },
457
- get getCachedMediaInfo() { return parts.getCachedMediaInfo; },
458
- get getContainerMediaInfo() { return parts.getContainerMediaInfo; },
459
- get localBaseUrl() { return parts.localBaseUrl; },
460
- get outputTimes() { return parts.outputTimes; },
461
- get outputs() { return parts.outputs; },
462
- get quality() { return parts.quality; },
463
- get qualityOffer() { return parts.qualityOffer; },
464
- get segmentDurationSec() { return parts.segmentDurationSec; },
465
- get sourceFiles() { return parts.sourceFiles; },
466
- invalidateWaits: (output) => parts.serving.invalidateWaits(output),
467
- });
468
- // Answering a request for a playlist, an init segment or a segment: from the store when the piece is made and whole, otherwise held until it is.
469
- parts.serving = new SegmentServing({
470
- // What a key names, read back from the key: how to find a gone output's
471
- // stored pieces and whether they are cut at given times.
472
- segmentFormatOfKey,
473
- specOfKey: (key) => OutputSpec.fromKey(key),
474
- compareInits,
475
- activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
476
- viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
477
- buildMasterPlaylist: (...args) => parts.renditions.buildMasterPlaylist(...args),
478
- declaredTracks: (...args) => parts.renditions.declaredTracks(...args),
479
- publishedGridFor: (...args) => parts.outputTimes.publishedGridFor(...args),
480
- runStartTimeFor: (...args) => parts.outputTimes.runStartTimeFor(...args),
481
- get cushion() { return parts.cushion; },
482
- get encodeOrchestrator() { return parts.encodeOrchestrator; },
483
- get encodeRuns() { return parts.encodeRuns; },
484
- get hostTimings() { return parts.hostTimings; },
485
- get lookaheadSeconds() { return parts.lookaheadSeconds; },
486
- get outputTimes() { return parts.outputTimes; },
487
- get outputs() { return parts.outputs; },
488
- get segmentStore() { return parts.segmentStore; },
489
- get startupWaitMs() { return parts.startupWaitMs; },
490
- get viewers() { return parts.viewers; },
491
- });
492
- // How an output ends: disposed when nobody is left on it and it has been idle, or all at once on shutdown; and the segments an earlier process left behind adopted at startup.
493
- parts.lifecycle = new OutputLifecycle({
494
- invalidateWaits: (output) => parts.serving.invalidateWaits(output),
495
- segmentFormatOfKey,
496
- // Where the viewers of one output stand, in its segments: what the store
497
- // reads to give disk back in the right order.
498
- viewerSegmentsOn: (key) => viewerSegmentsOn({
499
- outputs: parts.outputs.values(),
500
- outputKey: key,
501
- segmentAt: (output, seconds) => parts.outputTimes.segmentIndexForTime(output, seconds),
502
- now: Date.now(),
503
- viewers: parts.viewers
504
- }),
505
- get budgetTimer() { return parts.budgetTimer; },
506
- get cleanupTimer() { return parts.cleanupTimer; },
507
- get encodeRuns() { return parts.encodeRuns; },
508
- get keyframeTables() { return parts.keyframeTables; },
509
- get machineBudget() { return parts.machineBudget; },
510
- get outputTimes() { return parts.outputTimes; },
511
- get outputs() { return parts.outputs; },
512
- get returns() { return parts.returns; },
513
- get segmentStore() { return parts.segmentStore; },
514
- get sessionTtlMs() { return parts.sessionTtlMs; },
515
- get sourceFiles() { return parts.sourceFiles; },
516
- get timelines() { return parts.timelines; },
517
- get viewers() { return parts.viewers; },
518
- });
519
- // Which output answers a request for a file, made if it is not here yet: the encoding component's decision, made without knowing who asked.
520
- parts.opening = new OutputOpening({
521
- logger,
522
- // The largest peak an output of this mode and rate control has been seen
523
- // carrying here: the only figure an encoder with no bound of its own has.
524
- observedPeakMbps: (spec) => parts.localObservations?.peakMbps(spec) ?? null,
525
- limitsFor: (frame) => parts.limitsFor(frame),
526
- probeMediaInfo: (url) => probeInputMediaInfo(parts.ffmpegBin, url),
527
- probeKeyframeTimes: (url, budgetMs) => probeVideoKeyframeTimes(parts.ffmpegBin, url, budgetMs),
528
- get decodeCostModel() { return parts.decodeCostModel; },
529
- get enabled() { return parts.enabled; },
530
- get encodeCost() { return parts.encodeCost; },
531
- get encodeRuns() { return parts.encodeRuns; },
532
- get admission() { return parts.admission; },
533
- get getCachedMediaInfo() { return parts.getCachedMediaInfo; },
534
- get hostLoad() { return parts.hostLoad; },
535
- get hostTimings() { return parts.hostTimings; },
536
- get keyframeTables() { return parts.keyframeTables; },
537
- get localBaseUrl() { return parts.localBaseUrl; },
538
- get outputs() { return parts.outputs; },
539
- get renditions() { return parts.renditions; },
540
- get returns() { return parts.returns; },
541
- get segmentDurationSec() { return parts.segmentDurationSec; },
542
- get segmentFormat() { return parts.segmentFormat; },
543
- segmentOutputFiles,
544
- get softwarePresetBenchmark() { return parts.softwarePresetBenchmark; },
545
- get sourceFiles() { return parts.sourceFiles; },
546
- get timelines() { return parts.timelines; },
547
- get tonemapSupported() { return parts.tonemapSupported; },
548
- get videoEncoder() { return parts.encoders.current; },
549
- });
550
- // What a viewer asks for: an output of a file, a position, a report of progress.
551
- parts.viewerRequests = new ViewerRequests({
552
- // Whether this machine has a place for one more viewer on this output —
553
- // asked in the same synchronous stretch as they are put on it.
554
- admitsWatching: (output) => parts.admission.admitsWatching(output?.outputKey ?? ""),
555
- activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
556
- viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
557
- minimumBufferSecondsFor: (output) => minimumBufferSecondsOf(output),
558
- getSourceStats: (...args) => parts.getSourceStats?.(...args) ?? null,
559
- disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
560
- expectedFirstSegmentMs: (...args) => parts.hostTimings.expectedFirstSegmentMs(...args),
561
- expectedSessionCreateMs: (...args) => parts.hostTimings.expectedSessionCreateMs(...args),
562
- planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
563
- waitUntilReady: (...args) => parts.serving.waitUntilReady(...args),
564
- get encodeRuns() { return parts.encodeRuns; },
565
- // When this viewer's playback can start and run to the end: the viewer
566
- // component's forecast, which models the viewer's browser.
567
- playbackReadiness: { predict: predictPlaybackReadiness, forecastRate, RateTrend },
568
- encodeSpeedReadingOf: (output) => parts.encodeCost.latestSpeedReadingOf(output),
569
- projectedEncodeSpeedOf: (output) => parts.encodeCost.projectedSpeedOf(output),
570
- audioDescriptionOf,
571
- processingStartupSecondsOf: (output) => output.spec.carries === "audio-only" ?
572
- audioReadingFor(audioCalibration, { ...audioDescriptionOf(output),
573
- codec: audioDescriptionOf(output)?.codec ?? output.file.media?.audioCodec,
574
- transcode: output.spec.audio?.transcode })?.startupSeconds ?? 0 :
575
- Math.max(0, (startStopCost?.firstByteWaitSec ?? 0) - parts.segmentDurationSec /
576
- parts.encodeCost.projectedSpeedOf(output)),
577
- initialOutputBitsPerMediaSecondOf: (output) => {
578
- const description = audioDescriptionOf(output);
579
- const reference = audioReadingFor(audioCalibration, { codec: description?.codec, transcode: false });
580
- const audio = output.spec.audio ? output.spec.audio.transcode ? AUDIO_TRANSCODE_KBPS * 1000 :
581
- description?.bitrateKbps > 0 ? description.bitrateKbps * 1000 :
582
- reference ? reference.bytes * 8 / reference.durationSeconds : 0 : 0;
583
- const video = output.spec.video ? (output.spec.video.encode?.rateControl?.maxrateKbps ??
584
- output.file.media?.bitrateKbps ?? 0) * 1000 : 0;
585
- return video + audio;
586
- },
587
- get opening() { return parts.opening; },
588
- get outputTimes() { return parts.outputTimes; },
589
- get outputs() { return parts.outputs; },
590
- get lookaheadSeconds() { return parts.lookaheadSeconds; },
591
- get quality() { return parts.quality; },
592
- get qualityOffer() { return parts.qualityOffer; },
593
- get renditions() { return parts.renditions; },
594
- get segmentDurationSec() { return parts.segmentDurationSec; },
595
- get segmentStore() { return parts.segmentStore; },
596
- get sourceFiles() { return parts.sourceFiles; },
597
- get startupWaitMs() { return parts.startupWaitMs; },
598
- get viewers() { return parts.viewers; },
599
- invalidateWaits: (output) => parts.serving.invalidateWaits(output),
600
- // Whether a request of this generation is still taken, what it belongs to,
601
- // what answered it, and the hold a response keeps while it is being sent.
602
- acceptsGeneration: (consumerId, stated) => acceptsGeneration(parts.viewers, consumerId, stated),
603
- generationOfRequest: (consumerId, stated) => generationOfRequest(parts.viewers, consumerId, stated),
604
- noteGivenOutput: (consumerId, generation, askedHeight, segmentIndex, outputKey) =>
605
- noteGivenOutput(parts.viewers, consumerId, generation, askedHeight, segmentIndex, outputKey),
606
- holdForResponse: (consumerId, outputKey) => holdForResponse(parts.viewers, consumerId, outputKey),
607
- noteServingVerdict: (consumerId, verdict) => noteServingVerdict(parts.viewers, consumerId, verdict),
608
- servingVerdictOf: (consumerId) => servingVerdictOf(parts.viewers, consumerId),
609
- });
610
- // What this host takes to create an output and to produce its first segment, kept across restarts until the synthetic figure can replace it (CLAUDE.md, host timings).
611
- parts.hostTimings = new HostTimings({
612
- get segmentDurationSec() { return parts.segmentDurationSec; },
613
- get softwarePresetBenchmark() { return parts.softwarePresetBenchmark; },
614
- get stateDir() { return parts.stateDir; },
615
- });
616
- parts.enabled = Boolean(enabled);
617
- parts.ffmpegBin = ffmpegBin;
618
- parts.keyframeTables = keyframeTables;
619
- // Where measurements about this host are kept between runs. Empty means
620
- // beside the installed proxy; a deployment with somewhere persistent to
621
- // write names it (--state-dir).
622
- parts.stateDir = typeof stateDir === "string" ? stateDir : "";
623
- // Output container (fMP4/CMAF or MPEG-TS). Everything container-specific —
624
- // muxer args, file naming, playlist header, per-segment correction — lives
625
- // in this module; nothing here branches on the format.
626
- parts.segmentFormat = resolveSegmentFormat(segmentFormatId);
627
- // Optional accessor for media info the playback planner already probed for
628
- // (sourceKey, fileIndex), so session create can skip its own ffmpeg scan.
629
- parts.getCachedMediaInfo = typeof getCachedMediaInfo === "function" ? getCachedMediaInfo : null;
630
- // The file's audio tracks, for the master playlist's rendition group. Same
631
- // inventory the browser's audio menu is built from.
632
- parts.getCachedAudioTracks = typeof getCachedAudioTracks === "function" ? getCachedAudioTracks : null;
633
- // What a file declares about itself, read by the container layer from the
634
- // same header its track table comes from: format, duration, and where its
635
- // own timeline begins. The last of those is why this exists — a soundtrack
636
- // shipped as its own file has a timeline of its own, and asking ffmpeg for
637
- // it meant reading a header this proxy had already read.
638
- parts.getContainerMediaInfo =
639
- typeof getContainerMediaInfo === "function" ? getContainerMediaInfo : null;
640
- // Fetch one whole file of a source, as a bounded read rather than a
641
- // selection. Used to pull a soundtrack that ships beside the picture onto
642
- // the disk while the swarm has capacity to spare — see
643
- // `#fetchSpareSoundtracks`. Optional: a proxy wired without it simply reads
644
- // such a soundtrack when it is played.
645
- parts.fetchWholeFile = typeof fetchWholeFile === "function" ? fetchWholeFile : null;
646
- // Optional async accessor for a source's live download stats, used by the
647
- // realtime budget to tell a CPU limit from a download-starved input:
648
- // (sourceKey, fileIndex) => Promise<{ downloadSpeed, fileLength, fileProgress } | null>.
649
- parts.getSourceStats = typeof getSourceStats === "function" ? getSourceStats : null;
650
- parts.setPriorityMap = typeof setPriorityMap === "function" ? setPriorityMap : null;
651
- parts.contentionPenalties = contentionPenalties instanceof Map ? contentionPenalties : null;
652
- // Seconds of film per second when the picture is COPIED, measured at
653
- // startup. Nothing else prices that branch: the other benchmarks measure
654
- // encoding and decoding, and a copy does neither.
655
- parts.copySpeedX = Number.isFinite(copySpeedX) && copySpeedX > 0 ? copySpeedX : null;
656
- // Totals across every torrent this proxy holds, used to price what the
657
- // torrent itself costs the machine (item 7). Optional: a proxy wired
658
- // without it simply never learns that figure.
659
- parts.getTorrentTotals = typeof getTorrentTotals === "function" ? getTorrentTotals : null;
660
- // The spilled pieces, as a pair of closures over the torrent thread: what
661
- // they weigh and how to tell them their share. Not the pool — the pool is
662
- // on the other side of the thread boundary and this side holds none of it.
663
- parts.spillDisk = spillDisk;
664
- parts.wholeFiles = wholeFiles;
665
- parts.diagnostics = diagnostics;
666
- parts.diagnosticsRoot = diagnosticsRoot;
667
- parts.memoryClaimant = memoryClaimant;
668
- parts.budgetPolicy = budgetPolicy;
669
- // Detected H.264 encoder descriptor (hardware or software). Defaults to
670
- // software libx264 when no detection result is supplied. May be downgraded
671
- // to software at runtime if a hardware encode fails.
672
- parts.encoders = new EncoderSelection({ detected: videoEncoder, softwareDescriptor });
673
- // WHAT THIS HOST HAS SEEN ITS OWN ADMITTED ENCODES DO, kept between runs and
674
- // used only on the configuration it was seen on (roadmap item 97, step 14).
675
- // A refinement of figures that exist without it: nothing is selected,
676
- // admitted or served differently when it is empty. Absent where the startup
677
- // calibration was not run, which is only a wiring made without it.
678
- parts.localObservations = null;
679
- if (calibration?.fingerprint) {
680
- parts.localObservations = new LocalObservations({
681
- fingerprint: calibration.fingerprint,
682
- filePath: path.join(typeof stateDir === "string" && stateDir.length > 0 ? stateDir : PROXY_ROOT, "local-observations.json"),
683
- logger
684
- });
685
- parts.localObservations.load(calibration.kinds().map((kind) => configurationKeyOf(calibration.fingerprint, {
686
- kind,
687
- name: kind === "software" ? softwareDescriptor().name : (videoEncoder?.kind === kind ? videoEncoder.name : kind)
688
- })));
689
- }
690
- /**
691
- * What the segments an output has closed carried, from their sizes and the
692
- * spans its timeline gives them: the average over all of them and the
693
- * largest one.
694
- *
695
- * @param {object} session
696
- * @returns {{ averageKbps: number, peakKbps: number } | null}
697
- */
698
- const segmentRatesOf = (session) => {
699
- const sizes = parts.segmentStore.sizesOf(session.outputKey);
700
- const timeline = session.timeline;
701
- if (!timeline || sizes.size === 0) {
702
- return null;
703
- }
704
- let bits = 0;
705
- let seconds = 0;
706
- let peakKbps = 0;
707
- for (const [index, size] of sizes) {
708
- const start = timeline.publishedStartOf(index);
709
- const end = index < timeline.segmentCount ? timeline.publishedStartOf(index + 1) : null;
710
- if (!(Number.isFinite(start) && Number.isFinite(end) && end > start) || !(size > 0)) {
711
- continue;
712
- }
713
- bits += size * 8;
714
- seconds += end - start;
715
- peakKbps = Math.max(peakKbps, (size * 8) / (end - start) / 1000);
716
- }
717
- return seconds > 0 ? { averageKbps: bits / seconds / 1000, peakKbps } : null;
718
- };
719
- // The modes of the encoder IN USE NOW, as measured at startup: slowest
720
- // first, each with its throughput by size. Read through the selection rather
721
- // than copied, because the encoder in use can change — a failing device
722
- // moves this host to software for the rest of the process, and from then on
723
- // it is software's own modes that price and choose, not the device's.
724
- // Null where nothing was measured, and then nothing is re-encoded here.
725
- parts.calibration = calibration ?? null;
726
- const givenModes = Array.isArray(softwarePresetBenchmark) ? softwarePresetBenchmark : null;
727
- Object.defineProperty(parts, "softwarePresetBenchmark", {
728
- get: () => (parts.calibration
729
- ? parts.calibration.modesFor(parts.encoders.current?.kind)
730
- : givenModes),
731
- enumerable: true
732
- });
733
- // Host decode cost solved at startup from the calibration clips:
734
- // `a × Mpixel/s + b × Mbit/s + c` seconds of decoding per second of video.
735
- // A re-encode pays for this as well as for the encoder, and leaving it out
736
- // is what made the budget offer rungs this host ran at a third of realtime.
737
- // Null when the clips are missing or the fit was rejected — the budget then
738
- // prices the encoder alone, as it did before.
739
- parts.decodeCostModel = decodeCostModel ?? null;
740
- // Whether this ffmpeg build can tone-map HDR→SDR (zscale + tonemap filters).
741
- // Gates the tonemap chain for HDR sources on the software path.
742
- parts.tonemapSupported = Boolean(tonemapSupported);
743
- parts.segmentDurationSec = segmentDurationSec;
744
- // How far ahead of the viewer this proxy lets an encoder run, in seconds of
745
- // playback. Stated rather than kept private, because the browser's forward
746
- // buffer is bounded by the same quantity and used to carry a copy of its
747
- // own: a hand-written 30 s, justified in a comment by a DIFFERENT constant
748
- // (the eight segments that bound a request ahead of the ENCODE HEAD), so
749
- // three quarters of what the encoder had already produced was thrown away.
750
- // One figure, said by the side that owns it (roadmap item 4).
751
- parts.lookaheadSeconds = LOOKAHEAD_PAUSE_SECONDS;
752
- parts.sessionTtlMs = sessionTtlMs;
753
- parts.startupWaitMs = startupWaitMs;
754
- parts.localBaseUrl = buildHttpBaseUrl(localBindHost, localPort);
755
- // Everyone watching anything, one object per person rather than one per
756
- // person per output. What a viewer chose, where they are and which outputs
757
- // they are watching are facts about the person; kept per output they were
758
- // three copies of which two were always stale.
759
- // Every change to who is watching what re-decides which encoders should
760
- // exist, because that decision reads nothing else about viewers. It used to
761
- // be re-taken on a five-second timer instead, which made a just-created
762
- // output wait up to five seconds before anything noticed it had a viewer.
763
- parts.viewers = new Viewers({ onChange: () => parts.encodeRuns.planEncodersSoon() });
764
- // The outputs that exist, and every question about them: the picture a step
765
- // belongs to, the steps, the soundtracks, the height a step is named by.
766
- parts.outputs = new OutputCatalog({
767
- fileLengthOf: (session) => parts.hostLoad.fileLengthByKey.get(session.file.key) ?? 0,
768
- largestPieceOf: (address) => parts.segmentStore.largestPiece(address)
769
- });
770
- // What this host learned last time it ran. Without it every restart shows
771
- // the first viewer a figure with no measurement behind it.
772
- parts.hostTimings.loadHostTimings();
773
- // Where produced segments live, addressed by WHAT they are rather than by
774
- // which session's encoder wrote them. Two sessions of one output — two
775
- // viewers who opened the same film at different places — write into one
776
- // directory and each serves what the other has already made. Injectable so
777
- // a test can give it a root of its own.
778
- parts.segmentStore = segmentStore instanceof SegmentStore
779
- ? segmentStore
780
- : new SegmentStore({ logger });
781
- // The store has grown: whether it still fits its share is asked now rather
782
- // than on the next cleanup pass.
783
- parts.segmentStore.onPublished(() => parts.lifecycle.keepWithinRoomSoon());
784
- // A segment closed may be the one a viewer's move between two limits of a
785
- // height is waiting for.
786
- parts.segmentStore.onPublished((key, index) => parts.renditions.noteSegmentPublished(key, index));
787
- // What encoders there should be on each output, and where. Given the two
788
- // things only this class can answer: how many this machine can afford, and
789
- // how to make one.
790
- // What encoding costs this machine, and which heights follow from it. Given
791
- // what it cannot work out for itself: which sessions belong to one file, the
792
- // host's own readings AT THE MOMENT OF THE QUESTION rather than copied, how
793
- // a soundtrack is keyed, how many encoders are running, and what a file
794
- // costs merely by being fetched.
795
- parts.encodeCost = new EncodeCost({
796
- outputs: parts.outputs,
797
- host: () => ({
798
- benchmark: parts.softwarePresetBenchmark,
799
- decodeModel: parts.decodeCostModel,
800
- contentionPenalties: parts.contentionPenalties,
801
- copySpeedX: parts.copySpeedX,
802
- audioCalibration,
803
- audioDescriptionOf,
804
- availability: parts.hostLoad.hostAvailability,
805
- // WHICH encoder this host settled on. Only the software ladder is
806
- // benchmarked, so a reading taken off a hardware encoder cannot be
807
- // split into its decode and encode halves and is not filed as one.
808
- encoderKind: parts.encoders.current?.kind ?? null,
809
- // The slowest this output's mode has been seen running alone on
810
- // comparable material on this configuration, or null.
811
- observedAloneSpeed: (session) => parts.localObservations?.slowestAloneSpeed(session.spec, contentOf(session.file)) ?? null
812
- }),
813
- // HOW MANY ENCODER PROCESSES ARE RUNNING, asked of the one thing that
814
- // makes and unmakes them. This used to be two counts of one fact, taken
815
- // by walking the session registry — one per session, one per run — and
816
- // they agreed only while a session held at most one run.
817
- runningEncoders: () => parts.encodeOrchestrator.runningCount(),
818
- encodersRunningNow: () => parts.encodeOrchestrator.runningCount(),
819
- torrentCostSecFor: (session) => parts.hostLoad.torrentCostSecFor(session),
820
- runsFor: (session) => parts.encodeRuns.runsOf(session),
821
- stateFor: (session) => parts.encodeRuns.runStateOf(session)
822
- });
823
- // WHICH HEIGHTS ARE ON THE MENU, which is the arithmetic above plus three
824
- // things that are nothing to do with it: whose answer it is, what may never
825
- // be withdrawn, and when the answer may be reused.
826
- parts.qualityOffer = new QualityOffer({
827
- encodeCost: parts.encodeCost,
828
- occupiedCostSec: (fileKey) => parts.admission?.occupiedCost({ exceptFileKey: fileKey }).costSec ?? 0,
829
- occupancyKnownFor: (fileKey) => (parts.admission?.occupiedCost({ exceptFileKey: fileKey }).unpriced ?? 0) === 0,
830
- outputs: parts.outputs,
831
- stateFor: (session) => parts.encodeRuns.runStateOf(session),
832
- // WHICH HEIGHTS A LIVE VIEWER HAS ON SCREEN, as numbers. Who is watching
833
- // what is the viewer layer's, and which session is which height is the
834
- // film's shape; neither travels — what crosses is the list of heights.
835
- heightsOnScreen: (owner) => parts.quality.heightsOnScreen(owner),
836
- // WHAT THE SWARM IS DOING WITH THIS FILE. Three readings, taken by
837
- // whoever reads it and handed over as three numbers: the speed this
838
- // file's own interruptions demand, the megabytes a second a viewer draws
839
- // through it, and what a megabyte costs this process.
840
- supplyFor: (file) => ({
841
- requiredSpeed: parts.hostLoad.requiredSpeedFor(file.sourceKey, file.fileIndex),
842
- megabytesPerSecond: parts.hostLoad.torrentMegabytesPerSecond(
843
- file.sourceKey,
844
- file.fileIndex,
845
- file.lengthBytes ?? parts.hostLoad.fileLengthByKey.get(file.key) ?? null,
846
- file.durationSeconds
847
- ),
848
- costPerMegabyte: parts.hostLoad.observedTorrentCostPerMegabyte
849
- })
850
- });
851
- // The priority map, built from where the viewers are and handed to both
852
- // sides that act on it. The downloading lives in another thread, so its
853
- // copy travels over the worker channel.
854
- parts.priority = new PriorityOrchestrator({
855
- publish: ({ sourceKey, fileIndex, durationSeconds, zones }) => {
856
- void Promise.resolve(
857
- parts.setPriorityMap?.({ sourceKey, fileIndex, durationSeconds, zones })
858
- ).catch(() => {});
859
- },
860
- get viewers() { return parts.viewers; },
861
- // WHERE THE TWO FACTS MEET, and this is the only place that holds both.
862
- // Which step is on somebody's screen belongs to the person; which output
863
- // a step supersedes belongs to the film's shape. Neither layer is handed
864
- // the other — one gets a plain id, the other is read for one field.
865
- watchedBy: (session, viewer) => !parts.outputs.supersededBy(session, viewer.activeVariantId ?? null),
866
- allowanceFor: (session) => minimumBufferFrom({
867
- segmentSeconds: parts.segmentDurationSec,
868
- worstSupplyWaitSec: parts.hostLoad.supplyFor(session.file)?.worstWaitSec
869
- })?.seconds ?? parts.segmentDurationSec
870
- });
871
- // WHETHER THE WHOLE MACHINE HAS A PLACE for one more encoder, across outputs.
872
- // Given what it cannot hold itself: what runs (the orchestrator's), what is
873
- // being prepared (the viewers' records), what an output costs (the encoding
874
- // cost) and how much of the machine nobody has priced (the host's reading).
875
- parts.admission = new EncodeAdmission({
876
- liveRunsByAddress: () => parts.encodeOrchestrator.liveRunsByAddress(),
877
- preparedAddresses: () => {
878
- const addresses = new Set();
879
- for (const id of outputsBeingPrepared(parts.viewers)) {
880
- const key = parts.outputs.get(id)?.outputKey;
881
- if (key) {
882
- addresses.add(key);
883
- }
884
- }
885
- return addresses;
886
- },
887
- // Every output a present viewer RECEIVES — by the same rule the per-output
888
- // priority map is built by — that still has something left to make. The
889
- // place an output is opened on is held from the moment its viewer is put
890
- // on it, not from when the plan gets round to its first encoder.
891
- watchedAddresses: () => {
892
- const addresses = new Set();
893
- for (const session of parts.outputs.values()) {
894
- const address = session.outputKey;
895
- if (!address || addresses.has(address) || finishedOutput(session)) {
896
- continue;
897
- }
898
- for (const viewer of parts.viewers.forOutput(session).values()) {
899
- if (viewer.isPresent() && !parts.outputs.supersededBy(session, viewer.activeVariantId ?? null)) {
900
- addresses.add(address);
901
- break;
902
- }
903
- }
904
- }
905
- return addresses;
906
- },
907
- finished: (address) => parts.outputs.outputsOn(address).some((session) => finishedOutput(session)),
908
- loadOf: (address) => parts.encodeCost.loadOfOutput(address),
909
- loadForCandidate: (spec, file) => parts.encodeCost.loadForCandidate(spec, file),
910
- availability: () => parts.hostLoad.hostAvailability ?? null
911
- });
912
- parts.encodeOrchestrator = new EncodeOrchestrator({
913
- admission: parts.admission,
914
- // What the viewers actually waited for, by band. The ledger is the
915
- // priority layer's; the encoding is handed a way to ask it.
916
- describeWaits: (address) => waits.describe(address),
917
- maxRunsFor: (address) => parts.encodeRuns.maxRunsForOutput(address),
918
- makeRun: ({ address, from, to, because }) => parts.encodeRuns.makeRunAt(address, from, to, because),
919
- segmentSeconds: parts.segmentDurationSec,
920
- contentionPenalties: parts.contentionPenalties,
921
- startingSpeedFor: (address) => parts.encodeCost.speedForOutput(address),
922
- segmentCoverage,
923
- // HOW IT ASKS TO DECIDE AGAIN. A plan that refuses to place anything
924
- // because an output's input is away needs something to bring it back:
925
- // nothing about the state changes while the data is missing, so no event
926
- // arrives on its own.
927
- planSoon: () => parts.encodeRuns.planEncodersSoon(),
928
- logger
929
- });
930
- // What a start and a stop were measured to cost here, before any viewer
931
- // existed. Without it both read zero at a cold open, and zero is not
932
- // "unmeasured" — it is "free", which is what moved an encoder between two
933
- // adjacent numbers every half second in the field.
934
- parts.encodeOrchestrator.noteStartupCosts(startStopCost);
935
- // Where each file is cut, held once per file and grid rather than once per
936
- // session. Two sessions of one film MUST agree about this to the
937
- // millisecond — a segment made by either has to be appendable where the
938
- // other's would have gone — and until now they agreed by copying, which is
939
- // a thing somebody has to remember to do and which drifted twice in the
940
- // field. They share the table now.
941
- parts.timelines = new Timelines();
942
- // The files this proxy is serving, one object per file however many
943
- // sessions are of it. It holds the file's key — which every cache about a
944
- // file is keyed by — its name, and the facts a probe returned.
945
- parts.sourceFiles = new SourceFiles();
946
- parts.cleanupTimer = setInterval(() => {
947
- void parts.lifecycle.cleanupExpired();
948
- }, CLEANUP_INTERVAL_MS);
949
- parts.cleanupTimer.unref();
950
- // How long after material stops being read somebody asks for it again — the
951
- // one term of the keeping period that is guessed rather than measured, and
952
- // the only place it can be measured from.
953
- parts.returns = new Returns();
954
- // One owner of the disk, and the list of what takes it lives with the owner.
955
- parts.machineBudget = wireMachineBudget({
956
- segmentStore: parts.segmentStore,
957
- spill: parts.spillDisk,
958
- wholeFiles: parts.wholeFiles,
959
- diagnostics: parts.diagnostics,
960
- diagnosticsRoot: parts.diagnosticsRoot,
961
- memory: parts.memoryClaimant,
962
- policy: parts.budgetPolicy ?? undefined,
963
- readFree: freeBytesFor,
964
- logger
965
- });
966
- // Realtime-budget monitor: only meaningful for the software encoder with a
967
- // benchmark (the only path that can pick/step resolution). Cheap no-op scan
968
- // otherwise.
969
- // The quality budget: what each output is asked to step to, and the bitrate ceiling a viewer's link sets. Everything it reads of the rest of the proxy is listed here.
970
- parts.quality = new QualityController({
971
- // The longest an output of this mode has been seen taking to be ready for
972
- // a viewer moving onto it, in milliseconds, or null.
973
- observedPreparationMs: (output) => {
974
- const seconds = parts.localObservations?.longestPreparationSec(output?.spec) ?? null;
975
- return seconds === null ? null : seconds * 1000;
976
- },
977
- // WHAT ENCODING IS TOLD ABOUT A PERSON: values, by name. Not the viewer,
978
- // whose record belongs to the viewer layer and is written only there.
979
- consumersOn: (output) => consumersOn(parts.viewers, output),
980
- qualityModeOf: (output, consumerId) => qualityModeOf(parts.viewers, output, consumerId),
981
- stepOnScreenOf: (output, consumerId) => stepOnScreenOf(parts.viewers, output, consumerId),
982
- standingAskOf: (output, consumerId) => standingAskOf(parts.viewers, output, consumerId),
983
- askQualityOf: (output, consumerId, height, reason, now, urgent) =>
984
- askQualityOf(parts.viewers, output, consumerId, height, reason, now, urgent),
985
- // What a viewer's page said about their buffer and the picture they see
986
- // (roadmap item 98), as values.
987
- bufferOf: (output, consumerId, spanSec) => bufferOf(parts.viewers, output, consumerId, spanSec),
988
- visiblePictureOf: (output, consumerId) => visiblePictureOf(parts.viewers, output, consumerId),
989
- // How long this host takes to close a first segment: how soon another
990
- // output could have the piece a viewer needs.
991
- expectedFirstSegmentMs: () => parts.hostTimings.expectedFirstSegmentMs(),
992
- dropAskOf: (output, consumerId) => dropAskOf(parts.viewers, output, consumerId),
993
- // EACH viewer's own link and who is present: a thin link decides for the
994
- // person on it and for nobody else (roadmap item 97, step 11), so the
995
- // budget asks per viewer instead of taking the worst over all of them.
996
- presentOn: (output) => presentOn(parts.viewers, output),
997
- linkReportOf: (output, consumerId) => linkReportOf(parts.viewers, output, consumerId),
998
- // The soundtrack a viewer receives, as part of the load their link carries.
999
- viewerAudioLoadOf: (base, consumerId) => parts.renditions.viewerAudioLoadOf(base, consumerId),
1000
- // The first lever on a viewer's link: another limit of the height on their
1001
- // screen, prepared and moved to without their player being told.
1002
- prepareSameHeightSwitch: (output, consumerId, direction, reason) =>
1003
- parts.renditions.prepareSameHeightSwitch(output, consumerId, direction, reason),
1004
- sameHeightSwitchPending: (consumerId) => parts.renditions.sameHeightSwitchPending(consumerId),
1005
- sameHeightSwitchDirection: (consumerId) => parts.renditions.sameHeightSwitchDirection(consumerId),
1006
- cancelSameHeightSwitch: (consumerId, reason) => parts.renditions.cancelSameHeightSwitch(consumerId, reason),
1007
- heightReadyFor: (base, consumerId, height) => parts.renditions.heightReadyFor(base, consumerId, height),
1008
- isLive: (...args) => parts.encodeRuns.isLive(...args),
1009
- liveConsumers: (...args) => parts.renditions.liveConsumers(...args),
1010
- liveRunsOf: (...args) => parts.encodeRuns.liveRunsOf(...args),
1011
- producedNumbers: (...args) => parts.serving.producedNumbers(...args),
1012
- reportHostLoad: (...args) => parts.hostLoad.reportHostLoad(...args),
1013
- runStateOf: (...args) => parts.encodeRuns.runStateOf(...args),
1014
- sampleDownloadRates: (...args) => parts.hostLoad.sampleDownloadRates(...args),
1015
- get encodeCost() { return parts.encodeCost; },
1016
- get getSourceStats() { return parts.getSourceStats; },
1017
- get outputs() { return parts.outputs; },
1018
- get qualityOffer() { return parts.qualityOffer; },
1019
- get segmentDurationSec() { return parts.segmentDurationSec; },
1020
- segmentPaths,
1021
- get videoEncoder() { return parts.encoders.current; },
1022
- });
1023
- parts.budgetTimer = setInterval(() => {
1024
- parts.cushion.reportCushions();
1025
- void parts.quality.runQualityBudgetOnce();
1026
- }, BUDGET_CHECK_INTERVAL_MS);
1027
- parts.budgetTimer.unref();
1028
- return parts;
1029
- }
1
+ /**
2
+ * @file Wiring of the outputs, the viewers and the encoding.
3
+ *
4
+ * Builds each component and hands it the narrow host it reads, and nothing
5
+ * else. It holds no behaviour: every member that used to be a method of the
6
+ * session manager is a method of the component that owns it now. What it
7
+ * returns is the set of components and the settings they share, for
8
+ * `server.js` to give each route the ones that route asks.
9
+ */
10
+
11
+ import { logger } from "../../utils/logger.js";
12
+ import { KeyframeTables } from "../media/KeyframeTables.js";
13
+ import { waits } from "./WaitLedger.js";
14
+ import { readMachineState, readProcessCpuSeconds, readProxyCpuSeconds, readSystemCpu, shareOfMachine } from "../encode/host-load.js";
15
+ import { minimumBufferFrom } from "../torrent/supply-margin.js";
16
+ import { PriorityOrchestrator } from "../viewer/PriorityOrchestrator.js";
17
+ import { softwareDescriptor } from "../encode/hwaccel.js";
18
+ import { resolveSegmentFormat } from "../encode/segment-formats/index.js";
19
+ import { Timelines } from "../encode/output/Timeline.js";
20
+ import { SourceFiles } from "../media/SourceFile.js";
21
+ import { SegmentStore } from "../storage/segment-store/SegmentStore.js";
22
+ import { EncodeCost } from "../encode/quality/EncodeCost.js";
23
+ import { QualityOffer } from "../encode/quality/QualityOffer.js";
24
+ import { activeOutputFor } from "../viewer/active-output.js";
25
+ import {
26
+ acceptsGeneration,
27
+ askQualityOf,
28
+ audioBeingWarmedOf,
29
+ audioChoiceOf,
30
+ chooseAudioTrack,
31
+ chooseOutput,
32
+ chosenOutputOf,
33
+ consumersOn,
34
+ dropAskOf,
35
+ generationOfRequest,
36
+ givenOutputOf,
37
+ heightsChosenAs,
38
+ highestGivenSegmentOf,
39
+ holdForResponse,
40
+ linkMbpsOf,
41
+ linkReportOf,
42
+ bufferOf,
43
+ bufferedSecondsOf,
44
+ visiblePictureOf,
45
+ linkReportsOn,
46
+ noteAudioBeingWarmed,
47
+ noteGivenOutput,
48
+ noteSameHeightSwitch,
49
+ noteServingVerdict,
50
+ noteStepBeingWarmed,
51
+ noteStepOnScreen,
52
+ outputsBeingPrepared,
53
+ placeOn,
54
+ presentOn,
55
+ qualityModeOf,
56
+ sameHeightSwitchOf,
57
+ servingVerdictOf,
58
+ standingAskOf,
59
+ stepBeingWarmedOf,
60
+ stepBeingWarmedSinceOf,
61
+ stepOnScreenOf,
62
+ switchingOnto,
63
+ watches
64
+ } from "../viewer/choices.js";
65
+ import { viewerSecondsOn, viewerSegmentsOn } from "../viewer/positions.js";
66
+ import { Viewers } from "../viewer/Viewers.js";
67
+ import { OutputCatalog } from "../encode/output/OutputCatalog.js";
68
+ import { ViewerRequests } from "./ViewerRequests.js";
69
+ import { OutputLifecycle } from "./OutputLifecycle.js";
70
+ import { SegmentServing } from "./SegmentServing.js";
71
+ import { audioStartSecondsFor } from "../viewer/audio-start.js";
72
+ import { forecastRate, predictPlaybackReadiness, RateTrend } from "../viewer/playback-readiness.js";
73
+ import { audioRenditionName } from "../media/audio-inventory.js";
74
+ import { Renditions } from "../encode/Renditions.js";
75
+ import { CushionReport, LOOKAHEAD_PAUSE_SECONDS } from "../encode/CushionReport.js";
76
+ import { EncodeRuns } from "../encode/EncodeRuns.js";
77
+ import { OutputTimes } from "../encode/OutputTimes.js";
78
+ import { HostLoad } from "../encode/quality/HostLoad.js";
79
+ import { HostTimings } from "../encode/quality/HostTimings.js";
80
+ import { BUDGET_CHECK_INTERVAL_MS, QualityController } from "../encode/quality/QualityController.js";
81
+ import { EncodeOrchestrator } from "../encode/EncodeOrchestrator.js";
82
+ import { EncodeAdmission } from "../encode/EncodeAdmission.js";
83
+ import { EncoderSelection } from "../encode/EncoderSelection.js";
84
+ import { OutputOpening } from "../encode/OutputOpening.js";
85
+ import { segmentFormatOfKey } from "../encode/output-key-format.js";
86
+ import { OutputSpec } from "../encode/output/OutputSpec.js";
87
+ import { compareInits } from "../encode/segment-formats/init-compat.js";
88
+ import { nominalKbpsFor, AUDIO_TRANSCODE_KBPS } from "../encode/args.js";
89
+ import { audioReadingFor } from "../encode/audio-work-rate.js";
90
+ import { probeInputMediaInfo } from "../media/media-info-probe.js";
91
+ import { probeVideoKeyframeTimes } from "../media/keyframe-probe.js";
92
+ import { wireMachineBudget } from "../storage/wire.js";
93
+ import { Returns } from "../storage/returns.js";
94
+ import { freeBytesFor } from "../storage/free.js";
95
+ import path from "node:path";
96
+ import { contentOf, LocalObservations } from "../encode/LocalObservations.js";
97
+ import { configurationKeyOf } from "../encode/fingerprint.js";
98
+ import { PROXY_ROOT } from "../encode/quality/HostTimings.js";
99
+ import { qualityStateOf } from "../encode/quality/OutputQualityState.js";
100
+
101
+ // Where a variant and an audio rendition live under a session — `v/<height>/…`
102
+ // and `a/<track>/…` — is stated in `encode/output/playlists.js`, beside the lines that
103
+ // write those addresses into a master playlist. The routes that parse them back
104
+ // are in `server.js`.
105
+
106
+ const CLEANUP_INTERVAL_MS = 30_000;
107
+ const DEFAULT_SEGMENT_DURATION_SEC = 4;
108
+ // Idle TTL: a session is disposed this long after the last segment/playlist
109
+ // access. Long enough that a viewer who pauses, backgrounds the tab, or briefly
110
+ // turns the phone off can resume WITHOUT a cold ffmpeg restart (the warm session
111
+ // also backs the seamless auto-reconnect). ffmpeg stops producing at the
112
+ // look-ahead cap when idle, so a lingering session costs retained segments on
113
+ // disk, not sustained CPU. Active playback refreshes the timer on every segment
114
+ // fetch, so it never expires mid-watch.
115
+ // How long a session outlives the BROWSER, not the viewing. Since server
116
+ // 0.8.103 a browser that holds a session re-asserts it every 30 s, so an open
117
+ // tab never consumes this at all — not while paused, not across a three-hour
118
+ // film. What is left is the case where the browser has genuinely gone: the tab
119
+ // was killed without releasing, the phone slept, the network dropped. Keeping
120
+ // the session means such a viewer comes back to a warm encoder instead of
121
+ // waiting out a cold start; the cost while nobody is there is disk for the
122
+ // produced segments, since the encoder is suspended and burns no CPU, and that
123
+ // disk is already bounded by the pool's 10 GB cap with eviction. Thirty minutes
124
+ // covers a meal, a phone call or a lift ride.
125
+ const DEFAULT_SESSION_TTL_MS = 30 * 60 * 1000;
126
+ const DEFAULT_STARTUP_WAIT_MS = 5_000;
127
+
128
+ /**
129
+ * Convert a bind-all host address to the loopback address so that
130
+ * the HLS input URL is always reachable from the same machine.
131
+ *
132
+ * @param {string} host
133
+ * @returns {string}
134
+ */
135
+ function toLoopbackHost(host) {
136
+ if (host === "0.0.0.0" || host === "::") {
137
+ return "127.0.0.1";
138
+ }
139
+ return host;
140
+ }
141
+
142
+ /**
143
+ * Build the HTTP base URL (scheme + host + port) for the local proxy server.
144
+ *
145
+ * @param {string} host - Bind host (may be "0.0.0.0" or "::").
146
+ * @param {number} port
147
+ * @returns {string} e.g. "http://127.0.0.1:9090"
148
+ */
149
+ function buildHttpBaseUrl(host, port) {
150
+ const url = new URL("http://localhost");
151
+ url.hostname = toLoopbackHost(host);
152
+ url.port = String(port);
153
+ return url.origin;
154
+ }
155
+
156
+ /**
157
+ * @typedef {Object} WireOutputsOptions
158
+ * @property {boolean} enabled - Whether HLS transcoding is enabled.
159
+ * @property {string} ffmpegBin - Path to the ffmpeg executable.
160
+ * @property {string} localBindHost - Host the proxy HTTP server is bound to.
161
+ * @property {number} localPort - Port the proxy HTTP server is listening on.
162
+ * @property {number} [segmentDurationSec] - HLS segment length in seconds.
163
+ * @property {number} [sessionTtlMs] - Session idle TTL in milliseconds.
164
+ * @property {number} [startupWaitMs] - Max time to wait for the first playlist file.
165
+ * @property {string} [segmentFormatId] - Output container: "fmp4" (default)
166
+ * or "mpegts". See `../segment-formats/index.js`.
167
+ */
168
+
169
+ /**
170
+ * @typedef {Object} HlsSession
171
+ * @property {string} id - The name of the output it produces.
172
+ * @property {string} fileName - Display name of the file being transcoded.
173
+ * @property {import("../media/container/KeyframeTable.js").KeyframeTable} keyframes -
174
+ * Where this file's keyframes are. One object per file, held by every session
175
+ * of it, so a table read late still reaches them. Used to snap a source seek
176
+ * onto a known-valid position (see #startEncodeRun).
177
+ */
178
+
179
+ /**
180
+ * Build the components and connect them.
181
+ *
182
+ * @param {WireOutputsOptions} options
183
+ * @returns {object} The components, and the settings they read.
184
+ */
185
+ export function wireOutputs({
186
+ enabled,
187
+ ffmpegBin,
188
+ localBindHost,
189
+ localPort,
190
+ segmentDurationSec = DEFAULT_SEGMENT_DURATION_SEC,
191
+ sessionTtlMs = DEFAULT_SESSION_TTL_MS,
192
+ startupWaitMs = DEFAULT_STARTUP_WAIT_MS,
193
+ // Where every file's keyframe table lives, and the only thing that reads
194
+ // one. A session asks for its file's table and is handed the object every
195
+ // other reader of that file holds, so a table that arrives late reaches the
196
+ // sessions created before it. Built here when nothing supplied one, which
197
+ // is a registry with no reader: it answers "not read" about every file, and
198
+ // every picture is then re-encoded — the correct behaviour for a proxy
199
+ // wired without a container reader, and what every unit test gets.
200
+ keyframeTables = new KeyframeTables(),
201
+ videoEncoder = null,
202
+ softwarePresetBenchmark = null,
203
+ // What every encoder this host may use was qualified and measured to do at
204
+ // startup, by kind (`encode/calibration.js`). Takes the place of the one
205
+ // array above, which a test may still hand in on its own.
206
+ calibration = null,
207
+ decodeCostModel = null,
208
+ getSourceStats = null,
209
+ setPriorityMap = null,
210
+ // What a second job costs on this host, measured at startup. Null when it
211
+ // could not be measured, and then nothing is corrected — the alternative
212
+ // is inventing a penalty, which is the same fault as inventing a fill rate.
213
+ contentionPenalties = null,
214
+ copySpeedX = null,
215
+ audioCalibration = [],
216
+ tonemapSupported = false,
217
+ getCachedMediaInfo = null,
218
+ getCachedAudioTracks = null,
219
+ getContainerMediaInfo = null,
220
+ fetchWholeFile = null,
221
+ segmentFormatId = undefined,
222
+ stateDir = "",
223
+ segmentStore = null,
224
+ getTorrentTotals,
225
+ startStopCost = null,
226
+ spillDisk = null,
227
+ wholeFiles = null,
228
+ diagnostics = null,
229
+ diagnosticsRoot = "",
230
+ memoryClaimant = null,
231
+ budgetPolicy = null}) {
232
+ const parts = {};
233
+ const audioDescriptionOf = (output) => (getCachedAudioTracks?.({
234
+ sourceKey: output.file.sourceKey, fileIndex: output.spec.grid?.fileIndex ?? output.file.fileIndex
235
+ }) ?? []).find((track) => track.fileIndex === output.spec.audio?.fileIndex &&
236
+ track.sourceTrackIndex === output.spec.audio?.trackIndex) ?? null;
237
+ // Encode components receive only the storage operations they use. The
238
+ // concrete SegmentStore remains owned by this assembly and is never handed
239
+ // to the encode layer.
240
+ const segmentCoverage = {
241
+ provenNumbers: (address) => parts.segmentStore.provenNumbers(address),
242
+ announce: (address, index) => parts.segmentStore.announce(address, index),
243
+ filesHeld: (address) => parts.segmentStore.filesHeld(address),
244
+ clearUpAfter: (address, startedAt) => parts.segmentStore.clearUpAfter(address, startedAt)
245
+ };
246
+ const segmentFiles = {
247
+ pathFor: (address) => parts.segmentStore.pathFor(address),
248
+ initOf: (address) => parts.segmentStore.initOf(address),
249
+ directoryFor: (address) => parts.segmentStore.directoryFor(address),
250
+ publish: (address, makingName, format, read) => parts.segmentStore.publish(address, makingName, format, read),
251
+ closedBytesOf: (address, makingName) => parts.segmentStore.closedBytesOf(address, makingName),
252
+ mediaRangesOf: (address, index, where) => parts.segmentStore.mediaRangesOf(address, index, where),
253
+ remove: (address, index, because) => parts.segmentStore.remove(address, index, because)
254
+ };
255
+ const segmentOutputFiles = {
256
+ addresses: () => parts.segmentStore.addresses(),
257
+ isClosed: (address, index) => parts.segmentStore.isClosed(address, index),
258
+ lastReadAt: (address) => parts.segmentStore.lastReadAt(address),
259
+ directoryFor: (address) => parts.segmentStore.directoryFor(address),
260
+ useFormat: (address, format) => parts.segmentStore.useFormat(address, format)
261
+ };
262
+ const segmentPaths = {
263
+ pathOf: (address, index) => parts.segmentStore.pathOf(address, index),
264
+ sizesOf: (address) => parts.segmentStore.sizesOf(address)
265
+ };
266
+ /**
267
+ * Whether everything this output will ever serve is made: every segment of
268
+ * its timeline closed in the store. Such an output needs no encoder and
269
+ * holds no place, however many watch it.
270
+ *
271
+ * @param {object} session
272
+ * @returns {boolean}
273
+ */
274
+ const finishedOutput = (session) => {
275
+ const count = Number(session?.timeline?.segmentCount) || 0;
276
+ return count > 0 && parts.segmentStore.provenNumbers(session.outputKey).length >= count;
277
+ };
278
+ // The nominal limits a size may be produced at, highest first. ONE list, read
279
+ // by the opening of an output and by the move between limits of a height, so
280
+ // the two cannot disagree about which limits exist. Only the size's own until
281
+ // a set of lower limits is decided (roadmap item 97, step 14): a lower limit
282
+ // handed to a viewer must come with the page saying so. Asked with the whole
283
+ // frame, because the row is chosen by area (`limitRowFor`).
284
+ parts.limitsFor = (frame) => [nominalKbpsFor(frame)];
285
+ // What the torrent and the proxy itself spend on this host, and how fast each watched torrent moves.
286
+ parts.hostLoad = new HostLoad({
287
+ readMachineState,
288
+ readProcessCpuSeconds,
289
+ readProxyCpuSeconds,
290
+ readSystemCpu,
291
+ shareOfMachine,
292
+ liveRunsOf: (...args) => parts.encodeRuns.liveRunsOf(...args),
293
+ runStateOf: (...args) => parts.encodeRuns.runStateOf(...args),
294
+ get getSourceStats() { return parts.getSourceStats; },
295
+ get getTorrentTotals() { return parts.getTorrentTotals; },
296
+ get outputs() { return parts.outputs; },
297
+ });
298
+ // Where each segment of an output begins, and how that table is corrected from what the encoder produced.
299
+ parts.outputTimes = new OutputTimes({
300
+ logger,
301
+ runsOf: (...args) => parts.encodeRuns.runsOf(...args),
302
+ stopEncodeRun: (...args) => parts.encodeRuns.stopEncodeRun(...args),
303
+ planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
304
+ get outputs() { return parts.outputs; },
305
+ get segmentDurationSec() { return parts.segmentDurationSec; },
306
+ });
307
+ // The encoders of this proxy: built where the plan places them, followed while they run, accounted when they end.
308
+ parts.encodeRuns = new EncodeRuns({
309
+ logger,
310
+ // What this host is doing with an encode is learned each time a run has
311
+ // measured its processing speed, on every host.
312
+ noteRunSpeedMeasured: (session, run) => {
313
+ void parts.encodeCost.learnFrom(session, run);
314
+ },
315
+ // What an admitted encode was seen to do, filed under its configuration.
316
+ observeEncodeEnded: (session) => {
317
+ if (!parts.localObservations || !session?.spec?.video?.encode) {
318
+ return;
319
+ }
320
+ const alone = Number(qualityStateOf(session).lastAloneSpeed);
321
+ parts.localObservations.noteEncode({
322
+ spec: session.spec,
323
+ content: contentOf(session.file),
324
+ aloneSpeedX: Number.isFinite(alone) && alone > 0 ? alone : null,
325
+ segmentKbps: segmentRatesOf(session)
326
+ });
327
+ },
328
+ viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
329
+ inputOf: (...args) => parts.renditions.inputOf(...args),
330
+ producedNumbers: (...args) => parts.serving.producedNumbers(...args),
331
+ servesAudioSeparately: (...args) => parts.renditions.servesAudioSeparately(...args),
332
+ disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
333
+ get contentionPenalties() { return parts.contentionPenalties; },
334
+ get encodeCost() { return parts.encodeCost; },
335
+ get encodeOrchestrator() { return parts.encodeOrchestrator; },
336
+ get ffmpegBin() { return parts.ffmpegBin; },
337
+ get outputTimes() { return parts.outputTimes; },
338
+ get outputs() { return parts.outputs; },
339
+ get priority() { return parts.priority; },
340
+ get segmentDurationSec() { return parts.segmentDurationSec; },
341
+ segmentFiles,
342
+ get videoEncoder() { return parts.encoders.current; },
343
+ get encoders() { return parts.encoders; },
344
+ invalidateWaits: (output) => parts.serving.invalidateWaits(output),
345
+ productionFailed: (output) => parts.renditions.noteProductionFailed(output),
346
+ });
347
+ // How much film is ready in front of the viewers, said; and the spare soundtracks fetched once it is full.
348
+ parts.cushion = new CushionReport({
349
+ viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
350
+ linkReportsOn: (output) => linkReportsOn(parts.viewers, output),
351
+ SourceFiles,
352
+ logger,
353
+ producedNumbers: (...args) => parts.serving.producedNumbers(...args),
354
+ get encodeRuns() { return parts.encodeRuns; },
355
+ get fetchWholeFile() { return parts.fetchWholeFile; },
356
+ get getCachedAudioTracks() { return parts.getCachedAudioTracks; },
357
+ get hostLoad() { return parts.hostLoad; },
358
+ get lookaheadSeconds() { return parts.lookaheadSeconds; },
359
+ get outputTimes() { return parts.outputTimes; },
360
+ get outputs() { return parts.outputs; },
361
+ });
362
+ // The steps of a picture and its soundtracks: which output answers each, made when first asked for, and the master playlist listing them.
363
+ // The cushion this file needs, from its segment length and the worst
364
+ // interruption its supply has shown — one statement read by every operation
365
+ // that asks it.
366
+ const minimumBufferSecondsOf = (output) => minimumBufferFrom({
367
+ segmentSeconds: parts.segmentDurationSec,
368
+ worstSupplyWaitSec: parts.hostLoad.supplyFor(output.file)?.worstWaitSec
369
+ })?.seconds ?? null;
370
+ parts.renditions = new Renditions({
371
+ // Whether this proxy re-encodes at all: a soundtrack with no stated rate is
372
+ // re-encoded where it may be, and copied where it may not.
373
+ get transcodeEnabled() { return parts.enabled; },
374
+ observedPeakMbps: (spec) => parts.localObservations?.peakMbps(spec) ?? null,
375
+ // A viewer has been moved onto an output prepared for them: how long it
376
+ // took, and what they held.
377
+ notePreparation: (output, seconds, bufferedSec) =>
378
+ parts.localObservations?.notePreparation({ spec: output?.spec, seconds, bufferedSec }),
379
+ viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
380
+ audioStartSecondsFor: (args) => audioStartSecondsFor({ ...args, viewers: parts.viewers }),
381
+ activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
382
+ // WHAT ENCODING IS TOLD ABOUT A PERSON, and what it may tell the viewer
383
+ // layer about them: values and names, never the viewer itself. Steps and
384
+ // soundtracks are chosen, warmed and left per person, so this is the widest
385
+ // of the three sets — and every one of them is a call on the owner, which
386
+ // is what keeps one writer per fact.
387
+ viewerCountOn: (output) => parts.viewers.forOutput(output).size,
388
+ // Whether anything still stands on it — somebody watching, or an
389
+ // assignment not yet released. See `Viewers.stillNeeded`.
390
+ outputStillNeeded: (output) => parts.viewers.stillNeeded(output),
391
+ consumersOn: (output) => consumersOn(parts.viewers, output),
392
+ presentOn: (output) => presentOn(parts.viewers, output),
393
+ qualityModeOf: (output, consumerId) => qualityModeOf(parts.viewers, output, consumerId),
394
+ linkMbpsOf: (output, consumerId) => linkMbpsOf(parts.viewers, output, consumerId),
395
+ audioChoiceOf: (output, consumerId) => audioChoiceOf(parts.viewers, output, consumerId),
396
+ chooseAudioTrack: (output, consumerId, choice) =>
397
+ chooseAudioTrack(parts.viewers, output, consumerId, choice),
398
+ stepOnScreenOf: (output, consumerId) => stepOnScreenOf(parts.viewers, output, consumerId),
399
+ noteStepOnScreen: (output, consumerId, stepId) =>
400
+ noteStepOnScreen(parts.viewers, output, consumerId, stepId),
401
+ stepBeingWarmedOf: (output, consumerId) => stepBeingWarmedOf(parts.viewers, output, consumerId),
402
+ stepBeingWarmedSinceOf: (output, consumerId) => stepBeingWarmedSinceOf(parts.viewers, output, consumerId),
403
+ noteStepBeingWarmed: (output, consumerId, stepId) =>
404
+ noteStepBeingWarmed(parts.viewers, output, consumerId, stepId),
405
+ audioBeingWarmedOf: (output, consumerId) => audioBeingWarmedOf(parts.viewers, output, consumerId),
406
+ noteAudioBeingWarmed: (output, consumerId, renditionId) =>
407
+ noteAudioBeingWarmed(parts.viewers, output, consumerId, renditionId),
408
+ watches: (output, consumerId) => watches(parts.viewers, output, consumerId),
409
+ placeOn: (output, consumerId, seconds) => placeOn(parts.viewers, output, consumerId, seconds),
410
+ // A viewer's own assignments: which output answered a height and segment in
411
+ // one generation of their viewing, so a repeat is answered the same way.
412
+ // Values in and out, like everything above.
413
+ generationOfRequest: (consumerId, stated) => generationOfRequest(parts.viewers, consumerId, stated),
414
+ givenOutputOf: (consumerId, generation, askedHeight, segmentIndex) =>
415
+ givenOutputOf(parts.viewers, consumerId, generation, askedHeight, segmentIndex),
416
+ noteGivenOutput: (consumerId, generation, askedHeight, segmentIndex, outputKey) =>
417
+ noteGivenOutput(parts.viewers, consumerId, generation, askedHeight, segmentIndex, outputKey),
418
+ // The output this viewer was chosen at a height, and the rule's choice of
419
+ // it — the viewer's own record, never one per file.
420
+ chosenOutputOf: (consumerId, askedHeight) => chosenOutputOf(parts.viewers, consumerId, askedHeight),
421
+ chooseOutput: (consumerId, askedHeight, outputKey) => chooseOutput(parts.viewers, consumerId, askedHeight, outputKey),
422
+ noteServingVerdict: (consumerId, verdict) => noteServingVerdict(parts.viewers, consumerId, verdict),
423
+ // A move between two limits of the height on a viewer's screen (roadmap
424
+ // item 97, step 12): which heights their choice is the output on screen
425
+ // under, the segment they were last given, the move being prepared, and
426
+ // whether a segment is closed on the output being prepared.
427
+ limitsFor: (frame) => parts.limitsFor(frame),
428
+ heightsChosenAs: (consumerId, outputKey) => heightsChosenAs(parts.viewers, consumerId, outputKey),
429
+ highestGivenSegmentOf: (consumerId, askedHeight) => highestGivenSegmentOf(parts.viewers, consumerId, askedHeight),
430
+ sameHeightSwitchOf: (consumerId) => sameHeightSwitchOf(parts.viewers, consumerId),
431
+ noteSameHeightSwitch: (consumerId, value) => noteSameHeightSwitch(parts.viewers, consumerId, value),
432
+ switchingOnto: (output) => switchingOnto(parts.viewers, output),
433
+ // What a viewer holds, and the cushion this file needs before a move that
434
+ // is not urgent is made (roadmap item 98).
435
+ bufferedSecondsOf: (consumerId) => bufferedSecondsOf(parts.viewers, consumerId),
436
+ minimumBufferSecondsFor: (output) => minimumBufferSecondsOf(output),
437
+ // Whether the whole machine has a place for one more encoder on this output,
438
+ // asked before a preparation is recorded.
439
+ admitsPreparation: (output) => parts.admission.admitsPreparation(output?.outputKey ?? ""),
440
+ segmentClosed: (key, index) => parts.segmentStore.isClosed(key, index),
441
+ // What a gone output left in the store, and whether another output's header
442
+ // may stand in for its own.
443
+ storedPieceReady: (key, fileName) => parts.serving.hasStoredPiece(key, fileName),
444
+ headersCompatible: (goneKey, liveKey) => parts.serving.headersCompatible(goneKey, liveKey),
445
+ placeViewerOn: (...args) => parts.viewerRequests.placeViewerOn(...args),
446
+ audioRenditionName,
447
+ logger,
448
+ viewerLeaves: (...args) => parts.lifecycle.viewerLeaves(...args),
449
+ createOrGetSession: (...args) => parts.viewerRequests.createOrGetSession(...args),
450
+ planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
451
+ disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
452
+ viewerPositionOf: (...args) => parts.viewerRequests.viewerPositionOf(...args),
453
+ get encodeRuns() { return parts.encodeRuns; },
454
+ get fileStartTimeReads() { return parts.fileStartTimeReads; },
455
+ set fileStartTimeReads(value) { parts.fileStartTimeReads = value; },
456
+ get getCachedAudioTracks() { return parts.getCachedAudioTracks; },
457
+ get getCachedMediaInfo() { return parts.getCachedMediaInfo; },
458
+ get getContainerMediaInfo() { return parts.getContainerMediaInfo; },
459
+ get localBaseUrl() { return parts.localBaseUrl; },
460
+ get outputTimes() { return parts.outputTimes; },
461
+ get outputs() { return parts.outputs; },
462
+ get quality() { return parts.quality; },
463
+ get qualityOffer() { return parts.qualityOffer; },
464
+ get segmentDurationSec() { return parts.segmentDurationSec; },
465
+ get sourceFiles() { return parts.sourceFiles; },
466
+ invalidateWaits: (output) => parts.serving.invalidateWaits(output),
467
+ });
468
+ // Answering a request for a playlist, an init segment or a segment: from the store when the piece is made and whole, otherwise held until it is.
469
+ parts.serving = new SegmentServing({
470
+ // What a key names, read back from the key: how to find a gone output's
471
+ // stored pieces and whether they are cut at given times.
472
+ segmentFormatOfKey,
473
+ specOfKey: (key) => OutputSpec.fromKey(key),
474
+ compareInits,
475
+ activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
476
+ viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
477
+ buildMasterPlaylist: (...args) => parts.renditions.buildMasterPlaylist(...args),
478
+ declaredTracks: (...args) => parts.renditions.declaredTracks(...args),
479
+ publishedGridFor: (...args) => parts.outputTimes.publishedGridFor(...args),
480
+ runStartTimeFor: (...args) => parts.outputTimes.runStartTimeFor(...args),
481
+ get cushion() { return parts.cushion; },
482
+ get encodeOrchestrator() { return parts.encodeOrchestrator; },
483
+ get encodeRuns() { return parts.encodeRuns; },
484
+ get hostTimings() { return parts.hostTimings; },
485
+ get lookaheadSeconds() { return parts.lookaheadSeconds; },
486
+ get outputTimes() { return parts.outputTimes; },
487
+ get outputs() { return parts.outputs; },
488
+ get segmentStore() { return parts.segmentStore; },
489
+ get startupWaitMs() { return parts.startupWaitMs; },
490
+ get viewers() { return parts.viewers; },
491
+ });
492
+ // How an output ends: disposed when nobody is left on it and it has been idle, or all at once on shutdown; and the segments an earlier process left behind adopted at startup.
493
+ parts.lifecycle = new OutputLifecycle({
494
+ invalidateWaits: (output) => parts.serving.invalidateWaits(output),
495
+ segmentFormatOfKey,
496
+ // Where the viewers of one output stand, in its segments: what the store
497
+ // reads to give disk back in the right order.
498
+ viewerSegmentsOn: (key) => viewerSegmentsOn({
499
+ outputs: parts.outputs.values(),
500
+ outputKey: key,
501
+ segmentAt: (output, seconds) => parts.outputTimes.segmentIndexForTime(output, seconds),
502
+ now: Date.now(),
503
+ viewers: parts.viewers
504
+ }),
505
+ get budgetTimer() { return parts.budgetTimer; },
506
+ get cleanupTimer() { return parts.cleanupTimer; },
507
+ get encodeRuns() { return parts.encodeRuns; },
508
+ get keyframeTables() { return parts.keyframeTables; },
509
+ get machineBudget() { return parts.machineBudget; },
510
+ get outputTimes() { return parts.outputTimes; },
511
+ get outputs() { return parts.outputs; },
512
+ get returns() { return parts.returns; },
513
+ get segmentStore() { return parts.segmentStore; },
514
+ get sessionTtlMs() { return parts.sessionTtlMs; },
515
+ get sourceFiles() { return parts.sourceFiles; },
516
+ get timelines() { return parts.timelines; },
517
+ get viewers() { return parts.viewers; },
518
+ });
519
+ // Which output answers a request for a file, made if it is not here yet: the encoding component's decision, made without knowing who asked.
520
+ parts.opening = new OutputOpening({
521
+ logger,
522
+ // The largest peak an output of this mode and rate control has been seen
523
+ // carrying here: the only figure an encoder with no bound of its own has.
524
+ observedPeakMbps: (spec) => parts.localObservations?.peakMbps(spec) ?? null,
525
+ limitsFor: (frame) => parts.limitsFor(frame),
526
+ probeMediaInfo: (url) => probeInputMediaInfo(parts.ffmpegBin, url),
527
+ probeKeyframeTimes: (url, budgetMs) => probeVideoKeyframeTimes(parts.ffmpegBin, url, budgetMs),
528
+ get decodeCostModel() { return parts.decodeCostModel; },
529
+ get enabled() { return parts.enabled; },
530
+ get encodeCost() { return parts.encodeCost; },
531
+ get encodeRuns() { return parts.encodeRuns; },
532
+ get admission() { return parts.admission; },
533
+ get getCachedMediaInfo() { return parts.getCachedMediaInfo; },
534
+ get hostLoad() { return parts.hostLoad; },
535
+ get hostTimings() { return parts.hostTimings; },
536
+ get keyframeTables() { return parts.keyframeTables; },
537
+ get localBaseUrl() { return parts.localBaseUrl; },
538
+ get outputs() { return parts.outputs; },
539
+ get renditions() { return parts.renditions; },
540
+ get returns() { return parts.returns; },
541
+ get segmentDurationSec() { return parts.segmentDurationSec; },
542
+ get segmentFormat() { return parts.segmentFormat; },
543
+ segmentOutputFiles,
544
+ get softwarePresetBenchmark() { return parts.softwarePresetBenchmark; },
545
+ get sourceFiles() { return parts.sourceFiles; },
546
+ get timelines() { return parts.timelines; },
547
+ get tonemapSupported() { return parts.tonemapSupported; },
548
+ get videoEncoder() { return parts.encoders.current; },
549
+ });
550
+ // What a viewer asks for: an output of a file, a position, a report of progress.
551
+ parts.viewerRequests = new ViewerRequests({
552
+ // Whether this machine has a place for one more viewer on this output —
553
+ // asked in the same synchronous stretch as they are put on it.
554
+ admitsWatching: (output) => parts.admission.admitsWatching(output?.outputKey ?? ""),
555
+ activeOutputFor: (args) => activeOutputFor({ ...args, viewers: parts.viewers }),
556
+ viewerSecondsOn: (output, consumerId, now) => viewerSecondsOn(parts.viewers, output, consumerId, now),
557
+ minimumBufferSecondsFor: (output) => minimumBufferSecondsOf(output),
558
+ getSourceStats: (...args) => parts.getSourceStats?.(...args) ?? null,
559
+ disposeSession: (...args) => parts.lifecycle.disposeSession(...args),
560
+ expectedFirstSegmentMs: (...args) => parts.hostTimings.expectedFirstSegmentMs(...args),
561
+ expectedSessionCreateMs: (...args) => parts.hostTimings.expectedSessionCreateMs(...args),
562
+ planEncodersSoon: (...args) => parts.encodeRuns.planEncodersSoon(...args),
563
+ waitUntilReady: (...args) => parts.serving.waitUntilReady(...args),
564
+ get encodeRuns() { return parts.encodeRuns; },
565
+ // When this viewer's playback can start and run to the end: the viewer
566
+ // component's forecast, which models the viewer's browser.
567
+ playbackReadiness: { predict: predictPlaybackReadiness, forecastRate, RateTrend },
568
+ encodeSpeedReadingOf: (output) => parts.encodeCost.latestSpeedReadingOf(output),
569
+ projectedEncodeSpeedOf: (output) => parts.encodeCost.projectedSpeedOf(output),
570
+ audioDescriptionOf,
571
+ processingStartupSecondsOf: (output) => output.spec.carries === "audio-only" ?
572
+ audioReadingFor(audioCalibration, { ...audioDescriptionOf(output),
573
+ codec: audioDescriptionOf(output)?.codec ?? output.file.media?.audioCodec,
574
+ transcode: output.spec.audio?.transcode })?.startupSeconds ?? 0 :
575
+ Math.max(0, (startStopCost?.firstByteWaitSec ?? 0) - parts.segmentDurationSec /
576
+ parts.encodeCost.projectedSpeedOf(output)),
577
+ initialOutputBitsPerMediaSecondOf: (output) => {
578
+ const description = audioDescriptionOf(output);
579
+ const reference = audioReadingFor(audioCalibration, { codec: description?.codec, transcode: false });
580
+ const audio = output.spec.audio ? output.spec.audio.transcode ? AUDIO_TRANSCODE_KBPS * 1000 :
581
+ description?.bitrateKbps > 0 ? description.bitrateKbps * 1000 :
582
+ reference ? reference.bytes * 8 / reference.durationSeconds : 0 : 0;
583
+ const video = output.spec.video ? (output.spec.video.encode?.rateControl?.maxrateKbps ??
584
+ output.file.media?.bitrateKbps ?? 0) * 1000 : 0;
585
+ return video + audio;
586
+ },
587
+ get opening() { return parts.opening; },
588
+ get outputTimes() { return parts.outputTimes; },
589
+ get outputs() { return parts.outputs; },
590
+ get lookaheadSeconds() { return parts.lookaheadSeconds; },
591
+ get quality() { return parts.quality; },
592
+ get qualityOffer() { return parts.qualityOffer; },
593
+ get renditions() { return parts.renditions; },
594
+ get segmentDurationSec() { return parts.segmentDurationSec; },
595
+ get segmentStore() { return parts.segmentStore; },
596
+ get sourceFiles() { return parts.sourceFiles; },
597
+ get startupWaitMs() { return parts.startupWaitMs; },
598
+ get viewers() { return parts.viewers; },
599
+ invalidateWaits: (output) => parts.serving.invalidateWaits(output),
600
+ // Whether a request of this generation is still taken, what it belongs to,
601
+ // what answered it, and the hold a response keeps while it is being sent.
602
+ acceptsGeneration: (consumerId, stated) => acceptsGeneration(parts.viewers, consumerId, stated),
603
+ generationOfRequest: (consumerId, stated) => generationOfRequest(parts.viewers, consumerId, stated),
604
+ noteGivenOutput: (consumerId, generation, askedHeight, segmentIndex, outputKey) =>
605
+ noteGivenOutput(parts.viewers, consumerId, generation, askedHeight, segmentIndex, outputKey),
606
+ holdForResponse: (consumerId, outputKey) => holdForResponse(parts.viewers, consumerId, outputKey),
607
+ noteServingVerdict: (consumerId, verdict) => noteServingVerdict(parts.viewers, consumerId, verdict),
608
+ servingVerdictOf: (consumerId) => servingVerdictOf(parts.viewers, consumerId),
609
+ });
610
+ // What this host takes to create an output and to produce its first segment, kept across restarts until the synthetic figure can replace it (CLAUDE.md, host timings).
611
+ parts.hostTimings = new HostTimings({
612
+ get segmentDurationSec() { return parts.segmentDurationSec; },
613
+ get softwarePresetBenchmark() { return parts.softwarePresetBenchmark; },
614
+ get stateDir() { return parts.stateDir; },
615
+ });
616
+ parts.enabled = Boolean(enabled);
617
+ parts.ffmpegBin = ffmpegBin;
618
+ parts.keyframeTables = keyframeTables;
619
+ // Where measurements about this host are kept between runs. Empty means
620
+ // beside the installed proxy; a deployment with somewhere persistent to
621
+ // write names it (--state-dir).
622
+ parts.stateDir = typeof stateDir === "string" ? stateDir : "";
623
+ // Output container (fMP4/CMAF or MPEG-TS). Everything container-specific —
624
+ // muxer args, file naming, playlist header, per-segment correction — lives
625
+ // in this module; nothing here branches on the format.
626
+ parts.segmentFormat = resolveSegmentFormat(segmentFormatId);
627
+ // Optional accessor for media info the playback planner already probed for
628
+ // (sourceKey, fileIndex), so session create can skip its own ffmpeg scan.
629
+ parts.getCachedMediaInfo = typeof getCachedMediaInfo === "function" ? getCachedMediaInfo : null;
630
+ // The file's audio tracks, for the master playlist's rendition group. Same
631
+ // inventory the browser's audio menu is built from.
632
+ parts.getCachedAudioTracks = typeof getCachedAudioTracks === "function" ? getCachedAudioTracks : null;
633
+ // What a file declares about itself, read by the container layer from the
634
+ // same header its track table comes from: format, duration, and where its
635
+ // own timeline begins. The last of those is why this exists — a soundtrack
636
+ // shipped as its own file has a timeline of its own, and asking ffmpeg for
637
+ // it meant reading a header this proxy had already read.
638
+ parts.getContainerMediaInfo =
639
+ typeof getContainerMediaInfo === "function" ? getContainerMediaInfo : null;
640
+ // Fetch one whole file of a source, as a bounded read rather than a
641
+ // selection. Used to pull a soundtrack that ships beside the picture onto
642
+ // the disk while the swarm has capacity to spare — see
643
+ // `#fetchSpareSoundtracks`. Optional: a proxy wired without it simply reads
644
+ // such a soundtrack when it is played.
645
+ parts.fetchWholeFile = typeof fetchWholeFile === "function" ? fetchWholeFile : null;
646
+ // Optional async accessor for a source's live download stats, used by the
647
+ // realtime budget to tell a CPU limit from a download-starved input:
648
+ // (sourceKey, fileIndex) => Promise<{ downloadSpeed, fileLength, fileProgress } | null>.
649
+ parts.getSourceStats = typeof getSourceStats === "function" ? getSourceStats : null;
650
+ parts.setPriorityMap = typeof setPriorityMap === "function" ? setPriorityMap : null;
651
+ parts.contentionPenalties = contentionPenalties instanceof Map ? contentionPenalties : null;
652
+ // Seconds of film per second when the picture is COPIED, measured at
653
+ // startup. Nothing else prices that branch: the other benchmarks measure
654
+ // encoding and decoding, and a copy does neither.
655
+ parts.copySpeedX = Number.isFinite(copySpeedX) && copySpeedX > 0 ? copySpeedX : null;
656
+ // Totals across every torrent this proxy holds, used to price what the
657
+ // torrent itself costs the machine (item 7). Optional: a proxy wired
658
+ // without it simply never learns that figure.
659
+ parts.getTorrentTotals = typeof getTorrentTotals === "function" ? getTorrentTotals : null;
660
+ // The spilled pieces, as a pair of closures over the torrent thread: what
661
+ // they weigh and how to tell them their share. Not the pool — the pool is
662
+ // on the other side of the thread boundary and this side holds none of it.
663
+ parts.spillDisk = spillDisk;
664
+ parts.wholeFiles = wholeFiles;
665
+ parts.diagnostics = diagnostics;
666
+ parts.diagnosticsRoot = diagnosticsRoot;
667
+ parts.memoryClaimant = memoryClaimant;
668
+ parts.budgetPolicy = budgetPolicy;
669
+ // Detected H.264 encoder descriptor (hardware or software). Defaults to
670
+ // software libx264 when no detection result is supplied. May be downgraded
671
+ // to software at runtime if a hardware encode fails.
672
+ parts.encoders = new EncoderSelection({ detected: videoEncoder, softwareDescriptor });
673
+ // WHAT THIS HOST HAS SEEN ITS OWN ADMITTED ENCODES DO, kept between runs and
674
+ // used only on the configuration it was seen on (roadmap item 97, step 14).
675
+ // A refinement of figures that exist without it: nothing is selected,
676
+ // admitted or served differently when it is empty. Absent where the startup
677
+ // calibration was not run, which is only a wiring made without it.
678
+ parts.localObservations = null;
679
+ if (calibration?.fingerprint) {
680
+ parts.localObservations = new LocalObservations({
681
+ fingerprint: calibration.fingerprint,
682
+ filePath: path.join(typeof stateDir === "string" && stateDir.length > 0 ? stateDir : PROXY_ROOT, "local-observations.json"),
683
+ logger
684
+ });
685
+ parts.localObservations.load(calibration.kinds().map((kind) => configurationKeyOf(calibration.fingerprint, {
686
+ kind,
687
+ name: kind === "software" ? softwareDescriptor().name : (videoEncoder?.kind === kind ? videoEncoder.name : kind)
688
+ })));
689
+ }
690
+ /**
691
+ * What the segments an output has closed carried, from their sizes and the
692
+ * spans its timeline gives them: the average over all of them and the
693
+ * largest one.
694
+ *
695
+ * @param {object} session
696
+ * @returns {{ averageKbps: number, peakKbps: number } | null}
697
+ */
698
+ const segmentRatesOf = (session) => {
699
+ const sizes = parts.segmentStore.sizesOf(session.outputKey);
700
+ const timeline = session.timeline;
701
+ if (!timeline || sizes.size === 0) {
702
+ return null;
703
+ }
704
+ let bits = 0;
705
+ let seconds = 0;
706
+ let peakKbps = 0;
707
+ for (const [index, size] of sizes) {
708
+ const start = timeline.publishedStartOf(index);
709
+ const end = index < timeline.segmentCount ? timeline.publishedStartOf(index + 1) : null;
710
+ if (!(Number.isFinite(start) && Number.isFinite(end) && end > start) || !(size > 0)) {
711
+ continue;
712
+ }
713
+ bits += size * 8;
714
+ seconds += end - start;
715
+ peakKbps = Math.max(peakKbps, (size * 8) / (end - start) / 1000);
716
+ }
717
+ return seconds > 0 ? { averageKbps: bits / seconds / 1000, peakKbps } : null;
718
+ };
719
+ // The modes of the encoder IN USE NOW, as measured at startup: slowest
720
+ // first, each with its throughput by size. Read through the selection rather
721
+ // than copied, because the encoder in use can change — a failing device
722
+ // moves this host to software for the rest of the process, and from then on
723
+ // it is software's own modes that price and choose, not the device's.
724
+ // Null where nothing was measured, and then nothing is re-encoded here.
725
+ parts.calibration = calibration ?? null;
726
+ const givenModes = Array.isArray(softwarePresetBenchmark) ? softwarePresetBenchmark : null;
727
+ Object.defineProperty(parts, "softwarePresetBenchmark", {
728
+ get: () => (parts.calibration
729
+ ? parts.calibration.modesFor(parts.encoders.current?.kind)
730
+ : givenModes),
731
+ enumerable: true
732
+ });
733
+ // Host decode cost solved at startup from the calibration clips:
734
+ // `a × Mpixel/s + b × Mbit/s + c` seconds of decoding per second of video.
735
+ // A re-encode pays for this as well as for the encoder, and leaving it out
736
+ // is what made the budget offer rungs this host ran at a third of realtime.
737
+ // Null when the clips are missing or the fit was rejected — the budget then
738
+ // prices the encoder alone, as it did before.
739
+ parts.decodeCostModel = decodeCostModel ?? null;
740
+ // Whether this ffmpeg build can tone-map HDR→SDR (zscale + tonemap filters).
741
+ // Gates the tonemap chain for HDR sources on the software path.
742
+ parts.tonemapSupported = Boolean(tonemapSupported);
743
+ parts.segmentDurationSec = segmentDurationSec;
744
+ // How far ahead of the viewer this proxy lets an encoder run, in seconds of
745
+ // playback. Stated rather than kept private, because the browser's forward
746
+ // buffer is bounded by the same quantity and used to carry a copy of its
747
+ // own: a hand-written 30 s, justified in a comment by a DIFFERENT constant
748
+ // (the eight segments that bound a request ahead of the ENCODE HEAD), so
749
+ // three quarters of what the encoder had already produced was thrown away.
750
+ // One figure, said by the side that owns it (roadmap item 4).
751
+ parts.lookaheadSeconds = LOOKAHEAD_PAUSE_SECONDS;
752
+ parts.sessionTtlMs = sessionTtlMs;
753
+ parts.startupWaitMs = startupWaitMs;
754
+ parts.localBaseUrl = buildHttpBaseUrl(localBindHost, localPort);
755
+ // Everyone watching anything, one object per person rather than one per
756
+ // person per output. What a viewer chose, where they are and which outputs
757
+ // they are watching are facts about the person; kept per output they were
758
+ // three copies of which two were always stale.
759
+ // Every change to who is watching what re-decides which encoders should
760
+ // exist, because that decision reads nothing else about viewers. It used to
761
+ // be re-taken on a five-second timer instead, which made a just-created
762
+ // output wait up to five seconds before anything noticed it had a viewer.
763
+ parts.viewers = new Viewers({ onChange: () => parts.encodeRuns.planEncodersSoon() });
764
+ // The outputs that exist, and every question about them: the picture a step
765
+ // belongs to, the steps, the soundtracks, the height a step is named by.
766
+ parts.outputs = new OutputCatalog({
767
+ fileLengthOf: (session) => parts.hostLoad.fileLengthByKey.get(session.file.key) ?? 0,
768
+ largestPieceOf: (address) => parts.segmentStore.largestPiece(address)
769
+ });
770
+ // What this host learned last time it ran. Without it every restart shows
771
+ // the first viewer a figure with no measurement behind it.
772
+ parts.hostTimings.loadHostTimings();
773
+ // Where produced segments live, addressed by WHAT they are rather than by
774
+ // which session's encoder wrote them. Two sessions of one output — two
775
+ // viewers who opened the same film at different places — write into one
776
+ // directory and each serves what the other has already made. Injectable so
777
+ // a test can give it a root of its own.
778
+ parts.segmentStore = segmentStore instanceof SegmentStore
779
+ ? segmentStore
780
+ : new SegmentStore({ logger });
781
+ // The store has grown: whether it still fits its share is asked now rather
782
+ // than on the next cleanup pass.
783
+ parts.segmentStore.onPublished(() => parts.lifecycle.keepWithinRoomSoon());
784
+ // A segment closed may be the one a viewer's move between two limits of a
785
+ // height is waiting for.
786
+ parts.segmentStore.onPublished((key, index) => parts.renditions.noteSegmentPublished(key, index));
787
+ // What encoders there should be on each output, and where. Given the two
788
+ // things only this class can answer: how many this machine can afford, and
789
+ // how to make one.
790
+ // What encoding costs this machine, and which heights follow from it. Given
791
+ // what it cannot work out for itself: which sessions belong to one file, the
792
+ // host's own readings AT THE MOMENT OF THE QUESTION rather than copied, how
793
+ // a soundtrack is keyed, how many encoders are running, and what a file
794
+ // costs merely by being fetched.
795
+ parts.encodeCost = new EncodeCost({
796
+ outputs: parts.outputs,
797
+ host: () => ({
798
+ benchmark: parts.softwarePresetBenchmark,
799
+ decodeModel: parts.decodeCostModel,
800
+ contentionPenalties: parts.contentionPenalties,
801
+ copySpeedX: parts.copySpeedX,
802
+ audioCalibration,
803
+ audioDescriptionOf,
804
+ availability: parts.hostLoad.hostAvailability,
805
+ // WHICH encoder this host settled on. Only the software ladder is
806
+ // benchmarked, so a reading taken off a hardware encoder cannot be
807
+ // split into its decode and encode halves and is not filed as one.
808
+ encoderKind: parts.encoders.current?.kind ?? null,
809
+ // The slowest this output's mode has been seen running alone on
810
+ // comparable material on this configuration, or null.
811
+ observedAloneSpeed: (session) => parts.localObservations?.slowestAloneSpeed(session.spec, contentOf(session.file)) ?? null
812
+ }),
813
+ // HOW MANY ENCODER PROCESSES ARE RUNNING, asked of the one thing that
814
+ // makes and unmakes them. This used to be two counts of one fact, taken
815
+ // by walking the session registry — one per session, one per run — and
816
+ // they agreed only while a session held at most one run.
817
+ runningEncoders: () => parts.encodeOrchestrator.runningCount(),
818
+ encodersRunningNow: () => parts.encodeOrchestrator.runningCount(),
819
+ torrentCostSecFor: (session) => parts.hostLoad.torrentCostSecFor(session),
820
+ runsFor: (session) => parts.encodeRuns.runsOf(session),
821
+ stateFor: (session) => parts.encodeRuns.runStateOf(session)
822
+ });
823
+ // WHICH HEIGHTS ARE ON THE MENU, which is the arithmetic above plus three
824
+ // things that are nothing to do with it: whose answer it is, what may never
825
+ // be withdrawn, and when the answer may be reused.
826
+ parts.qualityOffer = new QualityOffer({
827
+ encodeCost: parts.encodeCost,
828
+ occupiedCostSec: (fileKey) => parts.admission?.occupiedCost({ exceptFileKey: fileKey }).costSec ?? 0,
829
+ occupancyKnownFor: (fileKey) => (parts.admission?.occupiedCost({ exceptFileKey: fileKey }).unpriced ?? 0) === 0,
830
+ outputs: parts.outputs,
831
+ stateFor: (session) => parts.encodeRuns.runStateOf(session),
832
+ // WHICH HEIGHTS A LIVE VIEWER HAS ON SCREEN, as numbers. Who is watching
833
+ // what is the viewer layer's, and which session is which height is the
834
+ // film's shape; neither travels — what crosses is the list of heights.
835
+ heightsOnScreen: (owner) => parts.quality.heightsOnScreen(owner),
836
+ // WHAT THE SWARM IS DOING WITH THIS FILE. Three readings, taken by
837
+ // whoever reads it and handed over as three numbers: the speed this
838
+ // file's own interruptions demand, the megabytes a second a viewer draws
839
+ // through it, and what a megabyte costs this process.
840
+ supplyFor: (file) => ({
841
+ requiredSpeed: parts.hostLoad.requiredSpeedFor(file.sourceKey, file.fileIndex),
842
+ megabytesPerSecond: parts.hostLoad.torrentMegabytesPerSecond(
843
+ file.sourceKey,
844
+ file.fileIndex,
845
+ file.lengthBytes ?? parts.hostLoad.fileLengthByKey.get(file.key) ?? null,
846
+ file.durationSeconds
847
+ ),
848
+ costPerMegabyte: parts.hostLoad.observedTorrentCostPerMegabyte
849
+ })
850
+ });
851
+ // The priority map, built from where the viewers are and handed to both
852
+ // sides that act on it. The downloading lives in another thread, so its
853
+ // copy travels over the worker channel.
854
+ parts.priority = new PriorityOrchestrator({
855
+ publish: ({ sourceKey, fileIndex, durationSeconds, zones }) => {
856
+ void Promise.resolve(
857
+ parts.setPriorityMap?.({ sourceKey, fileIndex, durationSeconds, zones })
858
+ ).catch(() => {});
859
+ },
860
+ get viewers() { return parts.viewers; },
861
+ // WHERE THE TWO FACTS MEET, and this is the only place that holds both.
862
+ // Which step is on somebody's screen belongs to the person; which output
863
+ // a step supersedes belongs to the film's shape. Neither layer is handed
864
+ // the other — one gets a plain id, the other is read for one field.
865
+ watchedBy: (session, viewer) => !parts.outputs.supersededBy(session, viewer.activeVariantId ?? null),
866
+ allowanceFor: (session) => minimumBufferFrom({
867
+ segmentSeconds: parts.segmentDurationSec,
868
+ worstSupplyWaitSec: parts.hostLoad.supplyFor(session.file)?.worstWaitSec
869
+ })?.seconds ?? parts.segmentDurationSec
870
+ });
871
+ // WHETHER THE WHOLE MACHINE HAS A PLACE for one more encoder, across outputs.
872
+ // Given what it cannot hold itself: what runs (the orchestrator's), what is
873
+ // being prepared (the viewers' records), what an output costs (the encoding
874
+ // cost) and how much of the machine nobody has priced (the host's reading).
875
+ parts.admission = new EncodeAdmission({
876
+ liveRunsByAddress: () => parts.encodeOrchestrator.liveRunsByAddress(),
877
+ preparedAddresses: () => {
878
+ const addresses = new Set();
879
+ for (const id of outputsBeingPrepared(parts.viewers)) {
880
+ const key = parts.outputs.get(id)?.outputKey;
881
+ if (key) {
882
+ addresses.add(key);
883
+ }
884
+ }
885
+ return addresses;
886
+ },
887
+ // Every output a present viewer RECEIVES — by the same rule the per-output
888
+ // priority map is built by — that still has something left to make. The
889
+ // place an output is opened on is held from the moment its viewer is put
890
+ // on it, not from when the plan gets round to its first encoder.
891
+ watchedAddresses: () => {
892
+ const addresses = new Set();
893
+ for (const session of parts.outputs.values()) {
894
+ const address = session.outputKey;
895
+ if (!address || addresses.has(address) || finishedOutput(session)) {
896
+ continue;
897
+ }
898
+ for (const viewer of parts.viewers.forOutput(session).values()) {
899
+ if (viewer.isPresent() && !parts.outputs.supersededBy(session, viewer.activeVariantId ?? null)) {
900
+ addresses.add(address);
901
+ break;
902
+ }
903
+ }
904
+ }
905
+ return addresses;
906
+ },
907
+ finished: (address) => parts.outputs.outputsOn(address).some((session) => finishedOutput(session)),
908
+ loadOf: (address) => parts.encodeCost.loadOfOutput(address),
909
+ loadForCandidate: (spec, file) => parts.encodeCost.loadForCandidate(spec, file),
910
+ availability: () => parts.hostLoad.hostAvailability ?? null
911
+ });
912
+ parts.encodeOrchestrator = new EncodeOrchestrator({
913
+ admission: parts.admission,
914
+ // What the viewers actually waited for, by band. The ledger is the
915
+ // priority layer's; the encoding is handed a way to ask it.
916
+ describeWaits: (address) => waits.describe(address),
917
+ maxRunsFor: (address) => parts.encodeRuns.maxRunsForOutput(address),
918
+ makeRun: ({ address, from, to, because }) => parts.encodeRuns.makeRunAt(address, from, to, because),
919
+ segmentSeconds: parts.segmentDurationSec,
920
+ contentionPenalties: parts.contentionPenalties,
921
+ startingSpeedFor: (address) => parts.encodeCost.speedForOutput(address),
922
+ segmentCoverage,
923
+ // HOW IT ASKS TO DECIDE AGAIN. A plan that refuses to place anything
924
+ // because an output's input is away needs something to bring it back:
925
+ // nothing about the state changes while the data is missing, so no event
926
+ // arrives on its own.
927
+ planSoon: () => parts.encodeRuns.planEncodersSoon(),
928
+ logger
929
+ });
930
+ // What a start and a stop were measured to cost here, before any viewer
931
+ // existed. Without it both read zero at a cold open, and zero is not
932
+ // "unmeasured" — it is "free", which is what moved an encoder between two
933
+ // adjacent numbers every half second in the field.
934
+ parts.encodeOrchestrator.noteStartupCosts(startStopCost);
935
+ // Where each file is cut, held once per file and grid rather than once per
936
+ // session. Two sessions of one film MUST agree about this to the
937
+ // millisecond — a segment made by either has to be appendable where the
938
+ // other's would have gone — and until now they agreed by copying, which is
939
+ // a thing somebody has to remember to do and which drifted twice in the
940
+ // field. They share the table now.
941
+ parts.timelines = new Timelines();
942
+ // The files this proxy is serving, one object per file however many
943
+ // sessions are of it. It holds the file's key — which every cache about a
944
+ // file is keyed by — its name, and the facts a probe returned.
945
+ parts.sourceFiles = new SourceFiles();
946
+ parts.cleanupTimer = setInterval(() => {
947
+ void parts.lifecycle.cleanupExpired();
948
+ }, CLEANUP_INTERVAL_MS);
949
+ parts.cleanupTimer.unref();
950
+ // How long after material stops being read somebody asks for it again — the
951
+ // one term of the keeping period that is guessed rather than measured, and
952
+ // the only place it can be measured from.
953
+ parts.returns = new Returns();
954
+ // One owner of the disk, and the list of what takes it lives with the owner.
955
+ parts.machineBudget = wireMachineBudget({
956
+ segmentStore: parts.segmentStore,
957
+ spill: parts.spillDisk,
958
+ wholeFiles: parts.wholeFiles,
959
+ diagnostics: parts.diagnostics,
960
+ diagnosticsRoot: parts.diagnosticsRoot,
961
+ memory: parts.memoryClaimant,
962
+ policy: parts.budgetPolicy ?? undefined,
963
+ readFree: freeBytesFor,
964
+ logger
965
+ });
966
+ // Realtime-budget monitor: only meaningful for the software encoder with a
967
+ // benchmark (the only path that can pick/step resolution). Cheap no-op scan
968
+ // otherwise.
969
+ // The quality budget: what each output is asked to step to, and the bitrate ceiling a viewer's link sets. Everything it reads of the rest of the proxy is listed here.
970
+ parts.quality = new QualityController({
971
+ // The longest an output of this mode has been seen taking to be ready for
972
+ // a viewer moving onto it, in milliseconds, or null.
973
+ observedPreparationMs: (output) => {
974
+ const seconds = parts.localObservations?.longestPreparationSec(output?.spec) ?? null;
975
+ return seconds === null ? null : seconds * 1000;
976
+ },
977
+ // WHAT ENCODING IS TOLD ABOUT A PERSON: values, by name. Not the viewer,
978
+ // whose record belongs to the viewer layer and is written only there.
979
+ consumersOn: (output) => consumersOn(parts.viewers, output),
980
+ qualityModeOf: (output, consumerId) => qualityModeOf(parts.viewers, output, consumerId),
981
+ stepOnScreenOf: (output, consumerId) => stepOnScreenOf(parts.viewers, output, consumerId),
982
+ standingAskOf: (output, consumerId) => standingAskOf(parts.viewers, output, consumerId),
983
+ askQualityOf: (output, consumerId, height, reason, now, urgent) =>
984
+ askQualityOf(parts.viewers, output, consumerId, height, reason, now, urgent),
985
+ // What a viewer's page said about their buffer and the picture they see
986
+ // (roadmap item 98), as values.
987
+ bufferOf: (output, consumerId, spanSec) => bufferOf(parts.viewers, output, consumerId, spanSec),
988
+ visiblePictureOf: (output, consumerId) => visiblePictureOf(parts.viewers, output, consumerId),
989
+ // How long this host takes to close a first segment: how soon another
990
+ // output could have the piece a viewer needs.
991
+ expectedFirstSegmentMs: () => parts.hostTimings.expectedFirstSegmentMs(),
992
+ dropAskOf: (output, consumerId) => dropAskOf(parts.viewers, output, consumerId),
993
+ // EACH viewer's own link and who is present: a thin link decides for the
994
+ // person on it and for nobody else (roadmap item 97, step 11), so the
995
+ // budget asks per viewer instead of taking the worst over all of them.
996
+ presentOn: (output) => presentOn(parts.viewers, output),
997
+ linkReportOf: (output, consumerId) => linkReportOf(parts.viewers, output, consumerId),
998
+ // The soundtrack a viewer receives, as part of the load their link carries.
999
+ viewerAudioLoadOf: (base, consumerId) => parts.renditions.viewerAudioLoadOf(base, consumerId),
1000
+ // The first lever on a viewer's link: another limit of the height on their
1001
+ // screen, prepared and moved to without their player being told.
1002
+ prepareSameHeightSwitch: (output, consumerId, direction, reason) =>
1003
+ parts.renditions.prepareSameHeightSwitch(output, consumerId, direction, reason),
1004
+ sameHeightSwitchPending: (consumerId) => parts.renditions.sameHeightSwitchPending(consumerId),
1005
+ sameHeightSwitchDirection: (consumerId) => parts.renditions.sameHeightSwitchDirection(consumerId),
1006
+ cancelSameHeightSwitch: (consumerId, reason) => parts.renditions.cancelSameHeightSwitch(consumerId, reason),
1007
+ heightReadyFor: (base, consumerId, height) => parts.renditions.heightReadyFor(base, consumerId, height),
1008
+ isLive: (...args) => parts.encodeRuns.isLive(...args),
1009
+ liveConsumers: (...args) => parts.renditions.liveConsumers(...args),
1010
+ liveRunsOf: (...args) => parts.encodeRuns.liveRunsOf(...args),
1011
+ producedNumbers: (...args) => parts.serving.producedNumbers(...args),
1012
+ reportHostLoad: (...args) => parts.hostLoad.reportHostLoad(...args),
1013
+ runStateOf: (...args) => parts.encodeRuns.runStateOf(...args),
1014
+ sampleDownloadRates: (...args) => parts.hostLoad.sampleDownloadRates(...args),
1015
+ get encodeCost() { return parts.encodeCost; },
1016
+ get getSourceStats() { return parts.getSourceStats; },
1017
+ get outputs() { return parts.outputs; },
1018
+ get qualityOffer() { return parts.qualityOffer; },
1019
+ get segmentDurationSec() { return parts.segmentDurationSec; },
1020
+ segmentPaths,
1021
+ get videoEncoder() { return parts.encoders.current; },
1022
+ });
1023
+ parts.budgetTimer = setInterval(() => {
1024
+ parts.cushion.reportCushions();
1025
+ void parts.quality.runQualityBudgetOnce();
1026
+ }, BUDGET_CHECK_INTERVAL_MS);
1027
+ parts.budgetTimer.unref();
1028
+ return parts;
1029
+ }