@torrent-tv/proxy 2.89.1 → 2.89.2

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 (442) 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 +6 -1
  13. package/CHANGELOG.md +2299 -2288
  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 +729 -729
  23. package/docs/encode-run-state.md +96 -96
  24. package/docs/logs.md +97 -97
  25. package/docs/playback-start-forecast.md +42 -8
  26. package/docs/socks5-egress-research.md +114 -114
  27. package/docs/storage-architecture.md +267 -267
  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 +380 -380
  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/services/encode/CoverageMap.js +428 -428
  104. package/services/encode/CushionReport.js +345 -345
  105. package/services/encode/EncodeAdmission.js +376 -376
  106. package/services/encode/EncodeOrchestrator.js +1217 -1217
  107. package/services/encode/EncodePlan.js +1366 -1366
  108. package/services/encode/EncodeRun.js +813 -813
  109. package/services/encode/Encoder.js +142 -142
  110. package/services/encode/EncoderSelection.js +38 -38
  111. package/services/encode/LocalObservations.js +359 -359
  112. package/services/encode/NvencEncoder.js +50 -50
  113. package/services/encode/OutputTimes.js +579 -579
  114. package/services/encode/QsvEncoder.js +58 -58
  115. package/services/encode/Renditions.js +2282 -2282
  116. package/services/encode/RunProgress.js +84 -84
  117. package/services/encode/SegmentDemand.js +95 -95
  118. package/services/encode/SoftwareEncoder.js +121 -121
  119. package/services/encode/V4l2m2mEncoder.js +53 -53
  120. package/services/encode/VaapiEncoder.js +66 -66
  121. package/services/encode/args.js +418 -418
  122. package/services/encode/available-share.js +89 -89
  123. package/services/encode/calibration.js +361 -361
  124. package/services/encode/contention.js +128 -128
  125. package/services/encode/decode-cost-fit.js +363 -363
  126. package/services/encode/encode-exit.js +114 -114
  127. package/services/encode/encode-run-state.js +551 -551
  128. package/services/encode/encoder-readings.js +45 -45
  129. package/services/encode/fingerprint.js +322 -322
  130. package/services/encode/host-load.js +174 -174
  131. package/services/encode/index.js +9 -9
  132. package/services/encode/learned-median.js +90 -90
  133. package/services/encode/output/EncodedOutput.js +57 -57
  134. package/services/encode/output/Output.js +131 -131
  135. package/services/encode/output/OutputCatalog.js +414 -414
  136. package/services/encode/output/OutputSpec.js +390 -390
  137. package/services/encode/output/Timeline.js +308 -308
  138. package/services/encode/output/cut-grid.js +107 -107
  139. package/services/encode/output/ladder.js +32 -32
  140. package/services/encode/output/playlists.js +284 -284
  141. package/services/encode/output/rates.js +125 -125
  142. package/services/encode/output-key-format.js +21 -21
  143. package/services/encode/quality/HostLoad.js +525 -525
  144. package/services/encode/quality/HostTimings.js +249 -249
  145. package/services/encode/quality/OutputQualityState.js +28 -28
  146. package/services/encode/quality/QualityController.js +935 -935
  147. package/services/encode/quality/QualityOffer.js +416 -416
  148. package/services/encode/quality/drain-threat.js +47 -47
  149. package/services/encode/quality/link-budget.js +349 -349
  150. package/services/encode/quality/output-format.js +319 -319
  151. package/services/encode/quality/serving-output.js +216 -216
  152. package/services/encode/quality/visible-rung.js +57 -57
  153. package/services/encode/run-budget.js +97 -97
  154. package/services/encode/run-costs.js +155 -155
  155. package/services/encode/run-inputs.js +42 -42
  156. package/services/encode/segment-formats/fmp4.js +476 -458
  157. package/services/encode/segment-formats/index.js +103 -85
  158. package/services/encode/segment-formats/init-compat.js +324 -324
  159. package/services/encode/segment-formats/mp4-boxes.js +604 -541
  160. package/services/encode/segment-formats/mpegts.js +134 -134
  161. package/services/encode/start-stop-cost.js +178 -178
  162. package/services/encode/throughput.js +97 -97
  163. package/services/encode/torrent-cost.js +88 -88
  164. package/services/identity/installation-id.js +38 -38
  165. package/services/media/SourceFile.js +298 -298
  166. package/services/media/SubtitleOrchestrator.js +167 -167
  167. package/services/media/container/KeyframeTable.js +272 -272
  168. package/services/media/container/ebml-reader.js +159 -159
  169. package/services/media/ffmpeg-banner.js +260 -260
  170. package/services/media/keyframe-probe.js +157 -157
  171. package/services/media/media-info-probe.js +93 -93
  172. package/services/media/playback-planner.js +931 -931
  173. package/services/media/tracks/AudioTrack.js +143 -143
  174. package/services/media/tracks/ImageSubtitleTrack.js +19 -19
  175. package/services/media/tracks/SubtitleTrack.js +38 -38
  176. package/services/media/tracks/VideoTrack.js +33 -33
  177. package/services/media/tracks/audio-bound.js +233 -233
  178. package/services/media/tracks/index.js +15 -15
  179. package/services/media/tracks/language-detect.js +174 -174
  180. package/services/server/OutputLifecycle.js +418 -418
  181. package/services/server/SegmentServing.js +1150 -1150
  182. package/services/server/ViewerRequests.js +790 -786
  183. package/services/server/WaitLedger.js +142 -142
  184. package/services/server/controllers/PlaybackController.js +40 -40
  185. package/services/server/controllers/SubtitleController.js +109 -109
  186. package/services/server/http-responses.js +60 -60
  187. package/services/server/transcode-session-files.js +325 -325
  188. package/services/server/wire-outputs.js +1024 -1020
  189. package/services/storage/Diagnostics.js +202 -202
  190. package/services/storage/MachineBudget.js +235 -235
  191. package/services/storage/allowance.js +107 -107
  192. package/services/storage/core-dumps.js +106 -106
  193. package/services/storage/files/CompletedFiles.js +391 -391
  194. package/services/storage/files/piece-from-whole-file.js +118 -118
  195. package/services/storage/free.js +71 -71
  196. package/services/storage/keep.js +48 -48
  197. package/services/storage/machine-memory.js +56 -56
  198. package/services/storage/memory-report.js +575 -575
  199. package/services/storage/piece-store/piece-disk-store.js +539 -539
  200. package/services/storage/piece-store/piece-lru.js +495 -495
  201. package/services/storage/returns.js +103 -103
  202. package/services/storage/segment-store/SegmentStore.js +1255 -1255
  203. package/services/storage/wire.js +175 -175
  204. package/services/torrent/demand/DemandRegister.js +202 -202
  205. package/services/torrent/demand/Urgency.js +137 -137
  206. package/services/torrent/demand/Window.js +118 -118
  207. package/services/torrent/demand/index.js +8 -8
  208. package/services/torrent/demand/pieces.js +140 -140
  209. package/services/torrent/download/SwarmSelection.js +386 -386
  210. package/services/torrent/download/registry.js +102 -102
  211. package/services/torrent/download/withdraw-claim.js +80 -80
  212. package/services/torrent/files.js +455 -455
  213. package/services/torrent/naming.js +619 -619
  214. package/services/torrent/piece-store-of.js +29 -29
  215. package/services/torrent/supply-margin.js +262 -262
  216. package/services/torrent/worker/background-fill.js +213 -213
  217. package/services/torrent/worker/channel.js +271 -271
  218. package/services/torrent/worker/client.js +836 -836
  219. package/services/torrent/worker/fastest-wires.js +342 -342
  220. package/services/torrent/worker/handle-state.js +23 -23
  221. package/services/torrent/worker/install-webrtc-shim.js +32 -32
  222. package/services/torrent/worker/piece-reader.js +1078 -1078
  223. package/services/torrent/worker/pool-adapter.js +371 -371
  224. package/services/torrent/worker/protocol.js +184 -184
  225. package/services/torrent/worker/resume-warm.js +107 -107
  226. package/services/torrent/worker/webrtc-shim.js +219 -219
  227. package/services/transport/delivery-probe.js +842 -842
  228. package/services/transport/health-collector.js +53 -53
  229. package/services/transport/nat-classifier.js +231 -231
  230. package/services/transport/packet-witness.js +808 -808
  231. package/services/transport/port-mapper.js +235 -235
  232. package/services/transport/registry-api.js +81 -81
  233. package/services/transport/tunnel-client.js +447 -447
  234. package/services/transport/usrsctp-state.js +175 -175
  235. package/services/transport/webrtc-manager.js +484 -484
  236. package/services/viewer/Assignments.js +340 -340
  237. package/services/viewer/PriorityOrchestrator.js +325 -325
  238. package/services/viewer/Viewer.js +691 -691
  239. package/services/viewer/Viewers.js +368 -368
  240. package/services/viewer/active-output.js +37 -37
  241. package/services/viewer/audio-start.js +46 -46
  242. package/services/viewer/buffer-trend.js +81 -81
  243. package/services/viewer/choices.js +647 -647
  244. package/services/viewer/media-time.js +355 -0
  245. package/services/{server → viewer}/playback-readiness.js +635 -516
  246. package/services/viewer/positions.js +126 -126
  247. package/services/viewer/report-intake.js +46 -46
  248. package/store/source-registry.js +71 -71
  249. package/test/asset-paths.test.js +28 -28
  250. package/test/audio-buffer-continuity.test.js +77 -70
  251. package/test/audio-inventory.test.js +212 -212
  252. package/test/audio-track-bitrate.test.js +40 -40
  253. package/test/auto-quality-step.test.js +707 -707
  254. package/test/available-share.test.js +76 -76
  255. package/test/background-fill.test.js +190 -190
  256. package/test/client-log-file.test.js +110 -110
  257. package/test/completed-files.test.js +115 -115
  258. package/test/concurrent-cost.test.js +148 -148
  259. package/test/container-media-info.test.js +228 -228
  260. package/test/contention.test.js +76 -76
  261. package/test/core-dumps.test.js +57 -57
  262. package/test/coverage-follows-the-disk.test.js +228 -228
  263. package/test/coverage-map.test.js +195 -195
  264. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  265. package/test/cut-times-timeline.test.js +65 -65
  266. package/test/cuts-follow-published-grid.test.js +109 -109
  267. package/test/data-channel-frame.test.js +63 -63
  268. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  269. package/test/dead-torrent-handle.test.js +52 -52
  270. package/test/declared-rates.test.js +116 -116
  271. package/test/declared-tracks.test.js +43 -43
  272. package/test/decode-cost-fit.test.js +202 -202
  273. package/test/decode-cost.test.js +462 -462
  274. package/test/delivery-probe.test.js +393 -393
  275. package/test/demand-register.test.js +206 -206
  276. package/test/dht-bootstrap.test.js +72 -72
  277. package/test/drain-threat.test.js +65 -65
  278. package/test/duplicate-add.test.js +48 -48
  279. package/test/encode-admission.test.js +146 -146
  280. package/test/encode-cost.test.js +283 -283
  281. package/test/encode-exit.test.js +111 -111
  282. package/test/encode-orchestrator.test.js +419 -419
  283. package/test/encode-plan-viewers.test.js +718 -718
  284. package/test/encode-plan.test.js +545 -545
  285. package/test/encode-run-state.test.js +314 -314
  286. package/test/encode-run.test.js +162 -162
  287. package/test/encode-slope.test.js +46 -46
  288. package/test/encoded-output.test.js +39 -39
  289. package/test/encoder-kinds.test.js +122 -122
  290. package/test/encoder-readings.test.js +46 -46
  291. package/test/every-claimant-is-told-its-share.test.js +152 -152
  292. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  293. package/test/failed-start-breaker.test.js +202 -202
  294. package/test/fastest-wires.test.js +143 -143
  295. package/test/ffmpeg-stream-counts.test.js +78 -78
  296. package/test/file-edges.test.js +191 -191
  297. package/test/fmp4-presentation-clock.test.js +146 -162
  298. package/test/fmp4-self-contained.test.js +80 -80
  299. package/test/fmp4-timestamps.test.js +140 -140
  300. package/test/fmp4-track-completeness.test.js +41 -41
  301. package/test/format-keyed-outputs.test.js +78 -78
  302. package/test/health-metrics.test.js +38 -38
  303. package/test/held-request-width.test.js +157 -157
  304. package/test/helpers/encode-run.js +136 -136
  305. package/test/helpers/manager.js +57 -57
  306. package/test/helpers/output-spec.js +63 -63
  307. package/test/host-load.test.js +68 -68
  308. package/test/index-accuracy-is-about-the-file.test.js +128 -128
  309. package/test/init-compat.test.js +219 -219
  310. package/test/input-lost-quiets-the-plan.test.js +261 -261
  311. package/test/input-unavailable.test.js +48 -48
  312. package/test/installation-id.test.js +39 -39
  313. package/test/keeping-period.test.js +83 -83
  314. package/test/keyframe-index-accuracy.test.js +188 -188
  315. package/test/keyframes-belong-to-the-file.test.js +249 -249
  316. package/test/learned-median.test.js +37 -37
  317. package/test/letting-go-asks-who-is-watching.test.js +191 -191
  318. package/test/limit-row-by-area.test.js +60 -60
  319. package/test/link-budget.test.js +112 -112
  320. package/test/link-probe.test.js +56 -56
  321. package/test/local-encoding-data.test.js +273 -273
  322. package/test/logger-repeats.test.js +134 -134
  323. package/test/look-ahead-coverage.test.js +56 -56
  324. package/test/manager-surface.test.js +292 -292
  325. package/test/matroska-cues-track.test.js +192 -192
  326. package/test/media-time.test.js +62 -0
  327. package/test/memory-budget.test.js +390 -390
  328. package/test/move-cost.test.js +216 -216
  329. package/test/mp4-subtitles.test.js +173 -173
  330. package/test/one-authority.test.js +285 -285
  331. package/test/one-budget.test.js +149 -149
  332. package/test/one-resource-divided.test.js +185 -185
  333. package/test/one-serving-output-per-height.test.js +458 -458
  334. package/test/orchestrator-wired.test.js +206 -206
  335. package/test/output-catalog.test.js +39 -39
  336. package/test/output-shape.test.js +21 -21
  337. package/test/output-spec.test.js +251 -251
  338. package/test/output-speed.test.js +88 -88
  339. package/test/outputs-being-prepared.test.js +40 -40
  340. package/test/packet-witness-ring.test.js +236 -236
  341. package/test/packet-witness.test.js +148 -148
  342. package/test/piece-disk-store.test.js +401 -401
  343. package/test/piece-from-whole-file.test.js +129 -129
  344. package/test/piece-lru.test.js +319 -319
  345. package/test/piece-reader.test.js +162 -162
  346. package/test/piece-selection-offset.test.js +85 -85
  347. package/test/piece-store-eviction.test.js +595 -595
  348. package/test/piece-store-never-refuses.test.js +153 -153
  349. package/test/piece-store-reservations.test.js +403 -403
  350. package/test/piece-store-slow-disk.test.js +159 -159
  351. package/test/piece-tail.test.js +97 -97
  352. package/test/plan-host-timings.test.js +68 -68
  353. package/test/plan-is-steady.test.js +225 -225
  354. package/test/playback-readiness.test.js +518 -483
  355. package/test/playback-start-regressions.test.js +101 -99
  356. package/test/priority-map-download.test.js +174 -174
  357. package/test/priority-map-emptied.test.js +204 -204
  358. package/test/priority-map-per-output.test.js +215 -215
  359. package/test/priority-map.test.js +163 -163
  360. package/test/probe-wedge-certainty.test.js +60 -60
  361. package/test/produced-copy-choice.test.js +213 -213
  362. package/test/published-timeline.test.js +83 -83
  363. package/test/quality-offer.test.js +162 -162
  364. package/test/quality-variants.test.js +1257 -1257
  365. package/test/rate-control-in-the-output.test.js +180 -180
  366. package/test/read-survives-withdrawal.test.js +164 -164
  367. package/test/read-window.test.js +365 -365
  368. package/test/resume-warm.test.js +39 -39
  369. package/test/run-graph-drift.test.js +37 -37
  370. package/test/run-inputs.test.js +80 -80
  371. package/test/run-intervals.test.js +100 -100
  372. package/test/run-position-follows-published-grid.test.js +89 -89
  373. package/test/run-progress.test.js +65 -65
  374. package/test/same-height-switch.test.js +664 -664
  375. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  376. package/test/seek-landing.test.js +109 -109
  377. package/test/seek-target-not-superseded.test.js +195 -195
  378. package/test/segment-closed-on-both-branches.test.js +96 -96
  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-judged-by-its-own-header.test.js +221 -221
  383. package/test/segment-store-eviction.test.js +247 -247
  384. package/test/segment-store.test.js +352 -352
  385. package/test/segment-true-start.test.js +86 -86
  386. package/test/segments-are-shared.test.js +176 -176
  387. package/test/send-chunk-bytes.test.js +86 -86
  388. package/test/serving-existing-output.test.js +105 -105
  389. package/test/serving-output.test.js +102 -102
  390. package/test/shared-piece-store.test.js +310 -310
  391. package/test/sidecar-naming.test.js +142 -142
  392. package/test/soundtrack-rate-bound.test.js +289 -289
  393. package/test/source-file.test.js +133 -133
  394. package/test/source-registry.test.js +18 -18
  395. package/test/split-a-stretch.test.js +139 -139
  396. package/test/stale-request-after-seek.test.js +158 -158
  397. package/test/startup-readings.test.js +124 -124
  398. package/test/stream-route.test.js +209 -209
  399. package/test/subtitle-cue-framing.test.js +200 -200
  400. package/test/subtitle-cue-source.test.js +102 -102
  401. package/test/subtitle-cursor.test.js +63 -63
  402. package/test/subtitle-defaults.test.js +118 -118
  403. package/test/subtitle-language.test.js +252 -252
  404. package/test/supply-margin.test.js +177 -177
  405. package/test/swarm-follows-readers.test.js +174 -174
  406. package/test/swarm-reach.test.js +130 -130
  407. package/test/swarm-selection.test.js +220 -220
  408. package/test/tail-duplication.test.js +167 -167
  409. package/test/the-channel-has-both-ends.test.js +91 -91
  410. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  411. package/test/thread-pool.test.js +53 -53
  412. package/test/timeline.test.js +84 -84
  413. package/test/torrent-contents.test.js +235 -235
  414. package/test/torrent-cost.test.js +71 -71
  415. package/test/torrent-files.test.js +221 -221
  416. package/test/torrent-naming.test.js +255 -255
  417. package/test/tracks-begin-together.test.js +209 -209
  418. package/test/tunnel-renewal.test.js +167 -167
  419. package/test/two-viewers-one-picture.test.js +504 -504
  420. package/test/upload-hurry.test.js +186 -186
  421. package/test/usrsctp-state.test.js +131 -131
  422. package/test/video-facts.test.js +102 -102
  423. package/test/viewer-assignments.test.js +143 -143
  424. package/test/viewer-outputs.test.js +285 -285
  425. package/test/viewer-presence.test.js +116 -116
  426. package/test/viewer-requests-admission.test.js +89 -89
  427. package/test/viewer-states.test.js +189 -189
  428. package/test/viewer-subtitle-subscription.test.js +96 -96
  429. package/test/viewer.test.js +139 -139
  430. package/test/viewing-generations.test.js +390 -390
  431. package/test/visible-rung.test.js +37 -37
  432. package/test/wait-ledger.test.js +100 -100
  433. package/test/webrtc-shim.test.js +149 -149
  434. package/test/wedge-certainty.test.js +131 -131
  435. package/test/whole-file-held-read.test.js +30 -30
  436. package/test/withdraw-piece-claim.test.js +212 -212
  437. package/test/worker-channel.test.js +158 -158
  438. package/utils/client-log-file.js +151 -151
  439. package/utils/logger.js +312 -312
  440. package/utils/parse-range.js +25 -25
  441. package/utils/perf.js +59 -59
  442. package/utils/torrent-source-key.js +38 -38
@@ -1,1257 +1,1257 @@
1
- /**
2
- * @file Quality variants: the master playlist, and what happens when the viewer
3
- * moves between rungs.
4
- *
5
- * What makes a mid-stream change of quality possible at all is that every
6
- * variant is cut at the SAME times, so a segment produced by one encoder can be
7
- * appended where another encoder's would have gone. The last test here pins
8
- * that property at its source; the rest cover the wiring that a route reaches —
9
- * a module test that imports a function directly cannot see a caller that never
10
- * calls it (2.9.124).
11
- */
12
-
13
- import test from "node:test";
14
- import { fakeProcess as fakeEncoder, startRunOn } from "./helpers/encode-run.js";
15
- import assert from "node:assert/strict";
16
- import { SourceFile } from "../services/media/SourceFile.js";
17
- import { Timeline } from "../services/encode/output/Timeline.js";
18
- import { mkdtemp, rm } from "node:fs/promises";
19
- import os from "node:os";
20
- import path from "node:path";
21
- import { costKindForSession } from "../services/encode/quality/EncodeCost.js";
22
- import { managerWithOwnStore } from "./helpers/manager.js";
23
- import { fmp4Format } from "../services/encode/segment-formats/fmp4.js";
24
- import { computeCutGrid } from "../services/encode/output/cut-grid.js";
25
- import { buildRunCommand, nearestKeyframeAtOrBefore } from "../services/encode/run-command.js";
26
- import { Output } from "../services/encode/output/Output.js";
27
- import { outputSpec } from "./helpers/output-spec.js";
28
- import { qualityStateOf } from "../services/encode/quality/OutputQualityState.js";
29
- import { chooseOutput, chosenOutputOf } from "../services/viewer/choices.js";
30
-
31
- const BASE_ID = "aaaaaaaabbbbcccc";
32
- const VARIANT_ID = "1111111122223333";
33
- const SECOND_VARIANT_ID = "9999999988887777";
34
- /** The one person these checks are about. Every viewer has a name. */
35
- const VIEWER = "viewer";
36
-
37
- /**
38
- * The rule has chosen `key` for this viewer at this height. It used to be one
39
- * record per file and height for everybody (`OutputCatalog.servedBy`); it is
40
- * the viewer's own now (roadmap item 97, step 11), so the viewer is registered
41
- * first — a choice kept for nobody is lost.
42
- *
43
- * @param {object} manager
44
- * @param {object} base
45
- * @param {number} height
46
- * @param {string} key
47
- * @returns {void}
48
- */
49
- function chooseFor(manager, base, height, key) {
50
- manager.viewers.of(base, VIEWER);
51
- chooseOutput(manager.viewers, VIEWER, height, key);
52
- }
53
-
54
- /**
55
- * Ask for a height as the viewer does. A request naming nobody is refused.
56
- *
57
- * @param {object} manager
58
- * @param {object} base
59
- * @param {number} height
60
- * @returns {Promise<object | null>}
61
- */
62
- function askFor(manager, base, height) {
63
- manager.viewers.of(base, VIEWER);
64
- return manager.renditions.resolveVariantSession(BASE_ID, height, -1, VIEWER);
65
- }
66
- const SEGMENT_SECONDS = 4;
67
-
68
- /**
69
- * A session shaped like a live one, without the ffmpeg run behind it.
70
- *
71
- * @param {{ id: string, encodeHeight: number, dirPath: string, transcodeVideo?: boolean, audioOnly?: boolean, audioSeparate?: boolean, audioSourceTrackIndex?: number }} params
72
- * @returns {object}
73
- */
74
- function fakeSession({
75
- id,
76
- encodeHeight,
77
- dirPath,
78
- transcodeVideo = true,
79
- audioOnly = false,
80
- audioSeparate = false,
81
- audioSourceTrackIndex = 0
82
- }) {
83
- return {
84
- id,
85
- get outputKey() { return this.spec.toKey(); },
86
- spec: outputSpec({
87
- transcodeVideo,
88
- audioOnly,
89
- audioSeparate,
90
- audioSourceTrackIndex,
91
- height: encodeHeight
92
- }),
93
- dirPath,
94
- // Where this file is cut, held by the file. A fixture that stated it
95
- // on the session was describing what production no longer does.
96
- timeline: new Timeline({
97
- boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
98
- cutGrid: "uniform"
99
- }),
100
- state: "ready",
101
- // The file's own facts, which is where the size and what decoding it costs
102
- // both come from: 1080p24 at 8 Mbit/s, the field file of 2026-08-17. A
103
- // fixture that assigned a cost object instead was stating an answer the
104
- // file now derives, so nothing it said reached the arithmetic.
105
- file: new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" }).learn({
106
- width: 1920,
107
- height: 1080,
108
- fps: 24,
109
- bitrateKbps: 8000
110
- }),
111
- // An ordinary session reads its own file, and its sound is inside it. The
112
- // three differ only for a soundtrack shipped as a file of its own.
113
- get inputFile() { return this.file; },
114
- get audioFile() { return this.file; },
115
- startedAt: Date.now(),
116
- lastAccessedAt: Date.now(),
117
- ffmpeg: null,
118
- lastError: "",
119
- segmentFormat: fmp4Format,
120
- transcodeVideo,
121
- transcodeAudio: true,
122
- audioTrackIndex: 0,
123
- // The shape this output is encoded AS, decided once for the output rather
124
- // than once per session.
125
- output: new Output({ encodeWidth: 0, encodeHeight, outputFps: 24, softwarePreset: null, applyTonemap: false }),
126
- encodeRunGeneration: 0,
127
- failedStartAt: -1,
128
- failedStartCount: 0,
129
- waitEpoch: 0,
130
- usesExplicitCuts: false,
131
- useSyntheticPlaylist: true,
132
- playlistText: "#EXTM3U\n",
133
- segmentCount: 100,
134
- progress: { state: "running", processedSeconds: 0, startPositionSeconds: 0, speed: "1.0x" }
135
- };
136
- }
137
-
138
-
139
- /**
140
- * @returns {Promise<{ manager: object, base: object, dirPath: string }>}
141
- */
142
- async function managerWithBase() {
143
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-"));
144
- // Its own store root — see `helpers/manager.js` for what sharing one cost.
145
- const { manager } = managerWithOwnStore();
146
- // 812p is what a viewport-sized budget actually produces — deliberately not a
147
- // ladder rung, because that is the case the master has to carry.
148
- const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
149
- manager.outputs.set(BASE_ID, base);
150
- return { manager, base, dirPath };
151
- }
152
-
153
- function startManagedRun(manager, output, options = {}) {
154
- const run = startRunOn(output, options);
155
- manager.encodeOrchestrator.adopt(output.outputKey, run);
156
- return run;
157
- }
158
-
159
- test("the master offers every rung, the session's own height among them", async (t) => {
160
- const { manager, dirPath } = await managerWithBase();
161
- t.after(async () => {
162
- await manager.lifecycle.disposeAll();
163
- await rm(dirPath, { recursive: true, force: true });
164
- });
165
-
166
- const master = manager.renditions.buildMasterPlaylist(BASE_ID);
167
-
168
- assert.ok(master, "a re-encoded 1080p source has rungs to choose between");
169
- const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
170
- assert.deepEqual(
171
- heights,
172
- [1080, 812, 720, 540, 480, 360, 240],
173
- "the source height, the height already being encoded, and the rungs below it, largest first"
174
- );
175
- assert.match(master, /^#EXT-X-VERSION:7$/m, "the version the segment format requires");
176
- assert.match(master, /RESOLUTION=1280x720/, "each variant states the size it decodes to");
177
- assert.ok(
178
- !master.includes("2160"),
179
- "a rung above the source would be upscaling — invented detail at a higher cost than the source"
180
- );
181
- });
182
-
183
- test("audio is published once for the file, and every rung points at it", async (t) => {
184
- const { manager, base, dirPath } = await managerWithBase();
185
- t.after(async () => {
186
- await manager.lifecycle.disposeAll();
187
- await rm(dirPath, { recursive: true, force: true });
188
- });
189
- // The inventory the plan already probed — the same list the browser's audio
190
- // menu is built from.
191
- manager.getCachedAudioTracks = () => [
192
- { index: 0, language: "rus", title: "Дубляж", isDefault: true },
193
- { index: 1, language: "eng", title: "", isDefault: false }
194
- ];
195
- // Settled at creation in production; set here directly, since this test
196
- // builds its session by hand.
197
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
198
- manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
199
-
200
- // ASKED FOR BY THE VIEWER WHOSE CHOICE IT IS. Which soundtrack a master marks
201
- // DEFAULT is a fact of the person the master is being built for — the route
202
- // passes the name of whoever asked — so a nameless request is answered by the
203
- // session's own parameters instead, which is another track entirely.
204
- const master = manager.renditions.buildMasterPlaylist(BASE_ID, VIEWER);
205
-
206
- assert.match(
207
- master,
208
- /#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="Дубляж",LANGUAGE="ru",AUTOSELECT=YES,DEFAULT=NO,URI="a\/0\/index\.m3u8"/,
209
- "a track with a title is named by it"
210
- );
211
- assert.match(
212
- master,
213
- /#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="eng",LANGUAGE="en",AUTOSELECT=YES,DEFAULT=YES,URI="a\/1\/index\.m3u8"/,
214
- "the track the session was created with is the default one, and an untitled track is named by its language"
215
- );
216
- const streams = [...master.matchAll(/^#EXT-X-STREAM-INF:.*$/gm)].map((match) => match[0]);
217
- assert.equal(streams.length, 7, "every rung");
218
- assert.ok(
219
- streams.every((line) => line.includes('AUDIO="aud"')),
220
- "each rung plays with the shared audio rather than carrying its own"
221
- );
222
- });
223
-
224
- test("a session that did not ask for renditions gets audio in its stream, as before", async (t) => {
225
- const { manager, dirPath } = await managerWithBase();
226
- t.after(async () => {
227
- await manager.lifecycle.disposeAll();
228
- await rm(dirPath, { recursive: true, force: true });
229
- });
230
- manager.getCachedAudioTracks = () => [{ index: 0, language: "rus", title: "", isDefault: true }];
231
-
232
- const master = manager.renditions.buildMasterPlaylist(BASE_ID);
233
-
234
- assert.ok(!master.includes("EXT-X-MEDIA"), "a browser that does not know about renditions is not sent any");
235
- assert.ok(!master.includes("AUDIO="), "and its rungs still carry their own audio");
236
- });
237
-
238
- test("a copied video is offered variants when its cut grid is real", async (t) => {
239
- const { manager, base, dirPath } = await managerWithBase();
240
- t.after(async () => {
241
- await manager.lifecycle.disposeAll();
242
- await rm(dirPath, { recursive: true, force: true });
243
- });
244
- // A copy is cut at the source's own keyframes — it has no other choice. A
245
- // re-encoded rung CAN be cut there too, by being told those times, and then
246
- // its segments cover the same spans and can stand in the copy's place.
247
- base.spec = outputSpec({ transcodeVideo: false, cutGrid: "keyframe" });
248
- base.timeline = new Timeline({ boundaries: base.timeline?.boundaries ?? [], cutGrid: "keyframe" });
249
-
250
- const master = manager.renditions.buildMasterPlaylist(BASE_ID);
251
-
252
- assert.ok(master, "the obstacle was never the encoder, it was the cut points");
253
- assert.match(master, /^v\/1080\/index\.m3u8$/m, "the copy itself is the top rung — no encoder, no cost");
254
- assert.match(master, /^v\/540\/index\.m3u8$/m);
255
- });
256
-
257
- test("a copied video with no readable keyframe index is offered nothing", async (t) => {
258
- const { manager, base, dirPath } = await managerWithBase();
259
- t.after(async () => {
260
- await manager.lifecycle.disposeAll();
261
- await rm(dirPath, { recursive: true, force: true });
262
- });
263
- // Its playlist claims an even grid that ffmpeg does not cut on. Aligning a
264
- // rung to that is aligning it to a fiction.
265
- base.spec = outputSpec({ transcodeVideo: false, cutGrid: "uniform" });
266
- base.timeline = new Timeline({ boundaries: base.timeline?.boundaries ?? [], cutGrid: "uniform" });
267
-
268
- assert.equal(manager.renditions.buildMasterPlaylist(BASE_ID), null);
269
- });
270
-
271
- test("the session's own height resolves to the session itself", async (t) => {
272
- const { manager, dirPath } = await managerWithBase();
273
- t.after(async () => {
274
- await manager.lifecycle.disposeAll();
275
- await rm(dirPath, { recursive: true, force: true });
276
- });
277
-
278
- assert.deepEqual(
279
- await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00000.mp4", VIEWER),
280
- { sessionId: BASE_ID },
281
- "an encoder is already producing this height; making a second one would be a cold start for nothing"
282
- );
283
- });
284
-
285
- test("a height the master does not offer is refused", async (t) => {
286
- const { manager, dirPath } = await managerWithBase();
287
- t.after(async () => {
288
- await manager.lifecycle.disposeAll();
289
- await rm(dirPath, { recursive: true, force: true });
290
- });
291
-
292
- assert.deepEqual(
293
- await manager.renditions.resolveVariantFile(BASE_ID, 999, "index.m3u8", VIEWER),
294
- { sessionId: null },
295
- "honouring an arbitrary height would let a client start encoder runs at will"
296
- );
297
- assert.deepEqual(
298
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "master.m3u8", VIEWER),
299
- { sessionId: null },
300
- "a master under a variant would describe variants of a variant"
301
- );
302
- });
303
-
304
- test("a variant's playlist is answered without starting an encoder for it", async (t) => {
305
- const { manager, dirPath } = await managerWithBase();
306
- t.after(async () => {
307
- await manager.lifecycle.disposeAll();
308
- await rm(dirPath, { recursive: true, force: true });
309
- });
310
-
311
- const resolved = await manager.renditions.resolveVariantFile(BASE_ID, 540, "index.m3u8", VIEWER);
312
-
313
- assert.deepEqual(
314
- resolved,
315
- { sessionId: BASE_ID },
316
- "every variant of a file has the same media playlist — that is what makes them interchangeable"
317
- );
318
- assert.equal(
319
- chosenOutputOf(manager.viewers, VIEWER, 540),
320
- "",
321
- "the player fetches a level's playlist to decide with, and may never switch to it"
322
- );
323
- });
324
-
325
- test("the rung the page says it plays is the viewer's rung, and the encoder goes with it", async (t) => {
326
- const { manager, base, dirPath } = await managerWithBase();
327
- t.after(async () => {
328
- await manager.lifecycle.disposeAll();
329
- await rm(dirPath, { recursive: true, force: true });
330
- });
331
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
332
- variant.variantHeight = 540;
333
- // A step of the picture: made as one, same file, and a height of its own.
334
- variant.isStep = true;
335
- manager.outputs.markStep(variant);
336
- manager.outputs.set(VARIANT_ID, variant);
337
- chooseFor(manager, base, 540, variant.outputKey);
338
- // The viewer is a hundred seconds in, and the base is the one encoding.
339
- base.lastRequestedSegment = 25;
340
- const encoder = fakeEncoder();
341
- startManagedRun(manager, base, { process: encoder });
342
- manager.encodeRuns.planEncodersSoon = () => {};
343
- const served = await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00025.mp4", VIEWER);
344
- assert.equal(served.sessionId, VARIANT_ID, "the file must be served from the variant, not the base");
345
- assert.equal(
346
- manager.viewers.of(base, VIEWER).activeVariantId ?? null,
347
- null,
348
- "a request for a rung's segment is the player fetching, not the person having moved"
349
- );
350
-
351
- // The page, the moment the player has switched: this rung, and the picture at 100 s.
352
- assert.equal(manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 100), true);
353
-
354
- assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, VARIANT_ID, "the variant the viewer is watching is the active one");
355
- assert.ok(
356
- Math.abs((manager.viewers.of(variant, VIEWER).positionSeconds() ?? -1) - 100) < 1,
357
- "where this person stands on the rung is where their picture is"
358
- );
359
- // AND THE RUNG THEY CAME OFF IS PRODUCING FOR NOBODY, which is one fact and
360
- // not an act. It used to be stopped from this path by hand, and the plan —
361
- // handed the whole film's priority map — started it again on the very next
362
- // pass, which this viewer's own move had just triggered.
363
- assert.equal(
364
- manager.outputs.supersededBy(base, manager.viewers.of(base, VIEWER).activeVariantId),
365
- true,
366
- "the picture they stepped off is nobody's now"
367
- );
368
- assert.equal(
369
- manager.outputs.supersededBy(variant, manager.viewers.of(variant, VIEWER).activeVariantId),
370
- false,
371
- "and the rung they moved to is theirs"
372
- );
373
- assert.deepEqual(encoder.signals, [], "stopping it is the plan's, from that fact, and not this path's");
374
- });
375
-
376
- test("a rung is placed where the picture is, not where the other rung had read to", async (t) => {
377
- const { manager, base, dirPath } = await managerWithBase();
378
- t.after(async () => {
379
- await manager.lifecycle.disposeAll();
380
- await rm(dirPath, { recursive: true, force: true });
381
- });
382
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
383
- variant.variantHeight = 540;
384
- // A step of the picture: made as one, same file, and a height of its own.
385
- variant.isStep = true;
386
- manager.outputs.markStep(variant);
387
- manager.outputs.set(VARIANT_ID, variant);
388
- chooseFor(manager, base, 540, variant.outputKey);
389
- startManagedRun(manager, base, { process: fakeEncoder() });
390
- // The rung being left had read fourteen segments further than the picture had
391
- // played — an encoder running at several times realtime fills the buffer far
392
- // ahead. Measured 2026-08-11: 56 s of gap, and using the read head placed the
393
- // new run past everything the player then asked for, which no request could
394
- // ever be answered from.
395
- base.lastRequestedSegment = 70;
396
-
397
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00056.mp4", VIEWER);
398
- manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 224);
399
-
400
- assert.equal(
401
- manager.viewers.of(variant, VIEWER).positionSeconds(),
402
- 224,
403
- "where the page says the picture is — 224 s, segment 56 on a four-second grid — " +
404
- "not the read head fourteen segments further on"
405
- );
406
- });
407
-
408
- test("warming a rung prepares it without taking the encoder from the one on screen", async (t) => {
409
- const { manager, base, dirPath } = await managerWithBase();
410
- t.after(async () => {
411
- await manager.lifecycle.disposeAll();
412
- await rm(dirPath, { recursive: true, force: true });
413
- });
414
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
415
- variant.variantHeight = 540;
416
- // A step of the picture: made as one, same file, and a height of its own.
417
- variant.isStep = true;
418
- manager.outputs.markStep(variant);
419
- manager.outputs.set(VARIANT_ID, variant);
420
- chooseFor(manager, base, 540, variant.outputKey);
421
- const encoder = fakeEncoder();
422
- startManagedRun(manager, base, { process: encoder });
423
- manager.encodeRuns.planEncodersSoon = () => {};
424
- const prepared = await manager.renditions.prepareVariant(BASE_ID, 540, 240, VIEWER);
425
-
426
- assert.deepEqual(
427
- prepared,
428
- { sessionId: VARIANT_ID, fileName: "segment-00060.mp4" },
429
- "the caller is told which segment to wait for — 240 s on a four-second grid"
430
- );
431
- assert.equal(
432
- manager.viewers.of(variant, VIEWER).positionSeconds(),
433
- 240,
434
- "the rung being warmed is told where this person is, which is what buys it an encoder"
435
- );
436
- assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, null, "nothing has switched yet");
437
- assert.equal([...base.runs][0]?.process, encoder, "the picture on screen keeps its encoder until the player actually moves");
438
- assert.deepEqual(encoder.signals, [], "stopping it here is what would put the spinner back");
439
- });
440
-
441
- test("a rung warmed at the playhead survives the switch that lands just ahead of it", async (t) => {
442
- const { manager, base, dirPath } = await managerWithBase();
443
- t.after(async () => {
444
- await manager.lifecycle.disposeAll();
445
- await rm(dirPath, { recursive: true, force: true });
446
- });
447
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
448
- variant.variantHeight = 540;
449
- // A step of the picture: made as one, same file, and a height of its own.
450
- variant.isStep = true;
451
- manager.outputs.markStep(variant);
452
- manager.outputs.set(VARIANT_ID, variant);
453
- chooseFor(manager, base, 540, variant.outputKey);
454
- startManagedRun(manager, base, { process: fakeEncoder() });
455
- // Warmed AT THE PLAYHEAD (240 s = segment #60), which is what the browser
456
- // sends from server 0.10.0 onwards, and the run is alive and has produced a
457
- // few segments past it.
458
- await manager.renditions.prepareVariant(BASE_ID, 540, 240, VIEWER);
459
-
460
- startManagedRun(manager, variant, { from: 59, process: fakeEncoder() });
461
- variant.progress = { ...variant.progress, processedSeconds: 268 };
462
- variant.seekTarget = null;
463
- variant.seekSettleTimer = null;
464
-
465
- // hls.js flushes from the fragment after the one holding
466
- // `currentTime + fetchdelay`, so its first request for the new rung is the
467
- // playhead plus up to one fragment — here #61 against a run that began at
468
- // #59. Warming at the END OF THE BUFFER instead put the run tens of seconds
469
- // AHEAD of this request, which the proxy then read as a seek backwards:
470
- // measured 2026-08-14, that killed a run holding 21.8 s of encoded output.
471
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00061.mp4", VIEWER);
472
- manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 244);
473
-
474
- assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, VARIANT_ID, "the viewer has moved to this rung");
475
- assert.equal(
476
- variant.seekTarget,
477
- null,
478
- "the request is inside the warmed run, so nothing is repositioned and the warm-up is kept"
479
- );
480
- assert.equal([...variant.runs][0].from, 59, "the run still begins where it was warmed");
481
- });
482
-
483
- test("a rung warmed PAST the switch is repositioned, which is what warming late costs", async (t) => {
484
- const { manager, base, dirPath } = await managerWithBase();
485
- t.after(async () => {
486
- await manager.lifecycle.disposeAll();
487
- await rm(dirPath, { recursive: true, force: true });
488
- });
489
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
490
- variant.variantHeight = 540;
491
- // A step of the picture: made as one, same file, and a height of its own.
492
- variant.isStep = true;
493
- manager.outputs.markStep(variant);
494
- manager.outputs.set(VARIANT_ID, variant);
495
- chooseFor(manager, base, 540, variant.outputKey);
496
- startManagedRun(manager, base, { process: fakeEncoder() });
497
- // The same session, warmed where the BUFFER ended rather than where the
498
- // picture was — 60 s further on, which is an ordinary cushion. This is what
499
- // server 0.9.3 sent and 0.11.0 stopped sending.
500
- await manager.renditions.prepareVariant(BASE_ID, 540, 300, VIEWER);
501
- startManagedRun(manager, variant, { from: 74, process: fakeEncoder() });
502
- variant.progress = { ...variant.progress, processedSeconds: 310 };
503
-
504
- // hls.js still lands near the playhead, so the request is far BEHIND the
505
- // warmed run: the proxy reads it as a seek backwards and starts again, and
506
- // everything the warm-up produced is thrown away. Measured in the field
507
- // 2026-08-14 as 21.8 s of encoded output destroyed by the act of using it.
508
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00061.mp4", VIEWER);
509
- manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 244);
510
-
511
- assert.equal(
512
- manager.viewers.of(variant, VIEWER).positionSeconds(),
513
- 244,
514
- "where the picture is, not where the warm-up had run to"
515
- );
516
- });
517
-
518
- test("the rung on screen fetching its own segments does not cancel a warm-up", async (t) => {
519
- const { manager, base, dirPath } = await managerWithBase();
520
- t.after(async () => {
521
- await manager.lifecycle.disposeAll();
522
- await rm(dirPath, { recursive: true, force: true });
523
- });
524
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
525
- variant.variantHeight = 540;
526
- // A step of the picture: made as one, same file, and a height of its own.
527
- variant.isStep = true;
528
- manager.outputs.markStep(variant);
529
- manager.outputs.set(VARIANT_ID, variant);
530
- chooseFor(manager, base, 540, variant.outputKey);
531
- const warmedEncoder = fakeEncoder();
532
- startManagedRun(manager, variant, { process: warmedEncoder });
533
- startManagedRun(manager, base, { process: fakeEncoder() });
534
- manager.encodeRuns.planEncodersSoon = () => {};
535
- await manager.renditions.prepareVariant(BASE_ID, 540, 100, VIEWER);
536
-
537
- // The viewer has not moved: the rung they are watching goes on asking for its
538
- // own segments, every few seconds, for as long as they watch.
539
- await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00026.mp4", VIEWER);
540
- manager.renditions.viewerPlays(BASE_ID, VIEWER, 812, 104);
541
- await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00027.mp4", VIEWER);
542
- manager.renditions.viewerPlays(BASE_ID, VIEWER, 812, 108);
543
-
544
- // Kept per viewer.
545
- assert.equal(
546
- manager.viewers.forOutput(base).get(VIEWER)?.warmingVariantId ?? null,
547
- VARIANT_ID,
548
- "the rung being prepared is still being prepared"
549
- );
550
- assert.deepEqual(
551
- warmedEncoder.signals,
552
- [],
553
- "cancelling it here left the viewer waiting out the whole warm-up for a segment nobody was making"
554
- );
555
- });
556
-
557
- test("warming the height the base itself serves still points it at the switch", async (t) => {
558
- const { manager, base, dirPath } = await managerWithBase();
559
- t.after(async () => {
560
- await manager.lifecycle.disposeAll();
561
- await rm(dirPath, { recursive: true, force: true });
562
- });
563
- // The viewer is on another rung; the base is parked where they left it, with
564
- // its encoder stopped. Warming its height must bring it back.
565
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
566
- variant.variantHeight = 540;
567
- manager.outputs.set(VARIANT_ID, variant);
568
- chooseFor(manager, base, 540, variant.outputKey);
569
- manager.viewers.of(base, VIEWER).activeVariantId = VARIANT_ID;
570
- base.runs = new Set();
571
-
572
- await manager.renditions.prepareVariant(BASE_ID, 812, 400, VIEWER);
573
-
574
- // 400 s falls on the boundary between #99 and #100, and a run starts one
575
- // segment back so the player has the preceding keyframe.
576
- assert.equal(
577
- manager.viewers.of(base, VIEWER).positionSeconds(),
578
- 396,
579
- "the base is parked where they left it, so warming its height says where they are like any other rung"
580
- );
581
- });
582
-
583
- test("the viewer's position is kept current by the segments they ask for", async (t) => {
584
- const { manager, base, dirPath } = await managerWithBase();
585
- t.after(async () => {
586
- await manager.lifecycle.disposeAll();
587
- await rm(dirPath, { recursive: true, force: true });
588
- });
589
- // A REQUEST SAYS NOTHING ABOUT WHERE THEY ARE, and asking for one must not
590
- // move them. Where they are is what they stated — a seek, or a report
591
- // carrying their playhead — and it stands until they state otherwise.
592
- manager.viewers.of(base, VIEWER).moveTo(40);
593
-
594
- await manager.serving.getFileStream(BASE_ID, "segment-00090.mp4", { consumerId: VIEWER });
595
-
596
- assert.ok(
597
- Math.abs((manager.viewers.of(base, VIEWER).positionSeconds() ?? -1) - 40) < 1,
598
- "a request for segment #90 leaves the viewer where they said they were"
599
- );
600
- });
601
-
602
- test("a playlist or an init segment does not move the encoder", async (t) => {
603
- const { manager, base, dirPath } = await managerWithBase();
604
- t.after(async () => {
605
- await manager.lifecycle.disposeAll();
606
- await rm(dirPath, { recursive: true, force: true });
607
- });
608
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
609
- manager.outputs.set(VARIANT_ID, variant);
610
- chooseFor(manager, base, 540, variant.outputKey);
611
- startManagedRun(manager, base, { process: fakeEncoder() });
612
- manager.encodeRuns.planEncodersSoon = () => {};
613
- chooseFor(manager, base, 540, variant.outputKey);
614
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "index.m3u8", VIEWER);
615
- await manager.renditions.resolveVariantFile(BASE_ID, 540, "init.mp4", VIEWER);
616
-
617
- assert.notEqual(
618
- manager.viewers.of(base, VIEWER).activeVariantId,
619
- VARIANT_ID,
620
- "hls.js fetches a level's playlist and init to decide with, and may never switch to it"
621
- );
622
- assert.ok([...base.runs][0]?.process, "the stream on screen must keep its encoder while the player is only looking");
623
- });
624
-
625
- test("the name of a variant is fixed, whatever its encode is later set to", async (t) => {
626
- const { manager, base, dirPath } = await managerWithBase();
627
- t.after(async () => {
628
- await manager.lifecycle.disposeAll();
629
- await rm(dirPath, { recursive: true, force: true });
630
- });
631
- // The player fetched the master once and addresses this variant as 812p for
632
- // the rest of the session, so the name must not follow the encode. Nothing in
633
- // the proxy changes `encodeHeight` mid-session any more — a change of size is
634
- // a change of variant now — but the name and the encode are still two
635
- // different things, and the addressing depends on their staying so.
636
- assert.equal(manager.outputs.variantHeightOf(base), 812);
637
- base.encodeHeight = 540;
638
-
639
- assert.equal(
640
- manager.outputs.variantHeightOf(base),
641
- 812,
642
- "the name stays; renaming it would leave the player addressing a variant nobody answers for"
643
- );
644
- assert.deepEqual(
645
- await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00000.mp4", VIEWER),
646
- { sessionId: BASE_ID },
647
- "a second session at a height the host has already failed to manage is the opposite of what a step is for"
648
- );
649
- });
650
-
651
- test("the cut grid follows the grid asked for, not who produces the frames", () => {
652
- // Why a segment from one encoder can stand where another's would have: both
653
- // are cut at the same times. Which times is a property of the SESSION — the
654
- // even grid, or the source's own keyframes — and it must not be re-derived
655
- // from whether the video is copied, because a variant of a copied stream is
656
- // re-encoded and still has to land on the copy's cuts.
657
- const shape = { durationSeconds: 100, segDur: SEGMENT_SECONDS, startTime: 0 };
658
- const keyframeTimes = [0, 3.1, 9.7, 14.2, 21.5, 40, 61.25];
659
-
660
- const even = computeCutGrid({ ...shape, useKeyframeGrid: false, keyframeTimes });
661
- assert.equal(even.boundaries[1], SEGMENT_SECONDS, "the even grid ignores the source's keyframes");
662
- assert.equal(even.boundaries.at(-1), 100);
663
-
664
- const source = computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes });
665
- assert.deepEqual(
666
- source.boundaries,
667
- [0, 9.7, 14.2, 21.5, 40, 61.25, 100],
668
- "the source's own keyframes, kept only where they are at least a segment apart"
669
- );
670
-
671
- // The one that matters: a copy and a re-encoded rung of it, given the same
672
- // grid, produce the SAME table. Segment N then covers the same span in both,
673
- // which is what lets one stand where the other would have.
674
- assert.deepEqual(
675
- computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes }).boundaries,
676
- source.boundaries,
677
- "a variant inherits the grid, so its boundaries are the same values"
678
- );
679
- // And with no index there is nothing to align to — the even grid, whoever asks.
680
- assert.deepEqual(
681
- computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes: null }).boundaries,
682
- even.boundaries,
683
- "no keyframes means no keyframe grid, however the caller asks"
684
- );
685
- });
686
-
687
- test("a boundary carries the keyframe it is, exactly as the container stated it", () => {
688
- // The fault that stopped a viewing on 2026-09-05. A boundary is kept on the
689
- // player's clock, `keyframe - startTime`, rounded; the seek used to add the
690
- // start time back and look the result up in the container's list by value.
691
- // The round trip is lossy — 26.234 - 0.083 + 0.083 is 26.233999999999998 —
692
- // and "the keyframe at or before that" is then the PREVIOUS one, a whole
693
- // keyframe interval earlier.
694
- const startTime = 0.083;
695
- const keyframeTimes = [];
696
- for (let index = 0; index < 60; index += 1) {
697
- keyframeTimes.push(Number((startTime + index * 8.717).toFixed(3)));
698
- }
699
- const grid = computeCutGrid({
700
- useKeyframeGrid: true, durationSeconds: 500, segDur: SEGMENT_SECONDS, keyframeTimes, startTime
701
- });
702
-
703
- assert.equal(grid.sourceTimes[0], startTime, "the first cut is the start of the file");
704
- assert.equal(grid.boundaries.length, grid.sourceTimes.length, "an index must name both clocks");
705
- for (let index = 1; index < grid.boundaries.length - 1; index += 1) {
706
- assert.ok(
707
- keyframeTimes.includes(grid.sourceTimes[index]),
708
- `cut #${index} carries ${grid.sourceTimes[index]}, which the container never stated`
709
- );
710
- }
711
-
712
- // What the round trip does, so the reason this table exists cannot be
713
- // mistaken for caution: at least one boundary fails to find itself.
714
- const lost = grid.boundaries
715
- .slice(1, -1)
716
- .filter((published, at) => nearestKeyframeAtOrBefore(keyframeTimes, published + startTime)
717
- !== grid.sourceTimes[at + 1]);
718
- assert.ok(
719
- lost.length > 0,
720
- "the search agreed everywhere, so this fixture no longer reproduces the fault it was built for"
721
- );
722
- });
723
-
724
- test("a run on the keyframe grid is given no trim to apply", () => {
725
- // The second half of the same fault. That trim is an output-side `-ss`, and
726
- // beside `-copyts` it moves the whole run backwards by its own amount:
727
- // measured 2026-09-06 on a 5 s keyframe interval, a run landing at 15 s and
728
- // asked to trim to the cut at 20 s produced its first file starting at 10 s.
729
- // Every cut of the run inherits it while the numbering, fixed at spawn, does
730
- // not — so the files are named for times they do not hold.
731
- const startTime = 0.083;
732
- const keyframeTimes = [];
733
- for (let index = 0; index < 60; index += 1) {
734
- keyframeTimes.push(Number((startTime + index * 8.717).toFixed(3)));
735
- }
736
- const grid = computeCutGrid({
737
- useKeyframeGrid: true, durationSeconds: 500, segDur: SEGMENT_SECONDS, keyframeTimes, startTime
738
- });
739
- const timeline = new Timeline({
740
- boundaries: grid.boundaries, sourceTimes: grid.sourceTimes, cutGrid: "keyframe"
741
- });
742
-
743
- for (let index = 1; index < grid.boundaries.length - 1; index += 1) {
744
- const { args } = buildRunCommand({
745
- keyframes: { times: keyframeTimes },
746
- inputFile: { startTime },
747
- audioFile: { startTime },
748
- inputUrl: "http://127.0.0.1/stream",
749
- audioInputUrl: "",
750
- outputDir: ".",
751
- timeline,
752
- segmentFormat: fmp4Format,
753
- transcodeVideo: false,
754
- transcodeAudio: true,
755
- audioOnly: false,
756
- audioSeparate: false,
757
- audioSourceTrackIndex: 0,
758
- rateControl: null,
759
- startIndex: index,
760
- endIndex: index,
761
- videoEncoder: { name: "libx264" },
762
- segmentDurationSec: SEGMENT_SECONDS
763
- });
764
- // One input seek establishes decode order in the preceding private cut.
765
- assert.equal(
766
- args.filter((one) => one === "-ss").length,
767
- 1,
768
- `run at #${index} was given a trim beside -copyts`
769
- );
770
- const seek = Number(args[args.indexOf("-ss") + 1]);
771
- assert.ok(
772
- Math.abs(seek - grid.sourceTimes[index - 1]) < 0.2,
773
- `run at #${index} seeks to ${seek}, not to the preceding keyframe ${grid.sourceTimes[index - 1]}`
774
- );
775
- assert.equal(Number(args[args.indexOf("-segment_start_number") + 1]), index - 1);
776
- }
777
- });
778
-
779
- test("a rung served by copy stays offered while a re-encoded rung is on screen", async (t) => {
780
- const { manager, base, dirPath } = await managerWithBase();
781
- t.after(async () => {
782
- await manager.lifecycle.disposeAll();
783
- await rm(dirPath, { recursive: true, force: true });
784
- });
785
- // The field case of 2026-08-15: a 1080p source served by COPY, the viewer on
786
- // 240p, and a host too weak to re-encode anything above it.
787
- base.spec = outputSpec({ transcodeVideo: false, cutGrid: "keyframe" });
788
- base.encodeHeight = 1080;
789
- base.variantHeight = 1080;
790
- // Enough to re-encode 240p (1.67x combined) and nowhere near enough for
791
- // 720p (0.45x) — the field's own shape, where the rung the viewer picked was
792
- // offered and everything between it and the copy was not.
793
- manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12_000_000 }];
794
- manager.decodeCostModel = { pixelTerm: 0.00793, bitrateTerm: 0, constantTerm: 0 };
795
- // What decoding this source costs comes from the file's own facts, stated in
796
- // the fixture: 49.766 Mpx/s at 8 Mbit/s.
797
- assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
798
-
799
- const watching = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
800
- watching.variantHeight = 240;
801
- // The rung knows the source as well as the base does, because it IS the same
802
- // file. Without that it prices nothing at all — every height comes back
803
- // "sustainable" for want of a measurement — and the assertion below would
804
- // hold for the wrong reason.
805
- watching.file = base.file;
806
- // A step of the picture: same file, and made as a step.
807
- watching.isStep = true;
808
- manager.outputs.markStep(watching);
809
- manager.outputs.set(VARIANT_ID, watching);
810
- chooseFor(manager, base, 240, watching.outputKey);
811
- manager.viewers.of(base, VIEWER).activeVariantId = VARIANT_ID;
812
-
813
- const offered = manager.quality.offeredHeights(watching);
814
-
815
- assert.ok(
816
- offered.includes(1080),
817
- "the height the source is COPIED at costs no encoder, so no measurement of this host can withdraw it"
818
- );
819
- assert.deepEqual(
820
- offered,
821
- manager.quality.offeredHeights(base),
822
- "one answer for the family: a rung asked while watching another must not disagree with the base"
823
- );
824
- });
825
-
826
- test("a separately published audio track starts where the picture is, from the reported buffer", async (t) => {
827
- const { manager, base, dirPath } = await managerWithBase();
828
- t.after(async () => {
829
- await manager.lifecycle.disposeAll();
830
- await rm(dirPath, { recursive: true, force: true });
831
- });
832
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
833
- manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
834
- // The viewer says where their picture is: 100 s. That, less a segment of
835
- // margin, is where the track has to begin — no subtraction of anything,
836
- // because the position is the playhead and not the edge of a buffer.
837
- manager.viewers.of(base, "viewer").moveTo(100);
838
- manager.viewers.of(base, "viewer").playing = false;
839
- manager.getCachedAudioTracks = () => [
840
- { index: 0, language: "rus", title: "", isDefault: true },
841
- { index: 1, language: "eng", title: "", isDefault: false }
842
- ];
843
- const created = [];
844
- manager.viewerRequests.createOrGetSession = async (params) => {
845
- created.push(params);
846
- // The output itself, which is what `createOrGetSession` answers, carrying
847
- // the track it was asked for.
848
- return fakeSession({
849
- id: VARIANT_ID,
850
- encodeHeight: 0,
851
- dirPath,
852
- audioOnly: true,
853
- audioSourceTrackIndex: params.audioTrackIndex
854
- });
855
- };
856
-
857
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
858
-
859
- assert.equal(created.length, 1, "the track's own session was made");
860
- assert.equal(
861
- created[0].startPositionSeconds,
862
- 96,
863
- "140 s served, less the 40 s the player holds, less one segment of margin"
864
- );
865
- });
866
-
867
- test("with two viewers the audio track starts at the EARLIEST picture, not the read head", async (t) => {
868
- const { manager, base, dirPath } = await managerWithBase();
869
- t.after(async () => {
870
- await manager.lifecycle.disposeAll();
871
- await rm(dirPath, { recursive: true, force: true });
872
- });
873
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
874
- // A copied picture is one session shared by both of them, and a track begun
875
- // at the leader has nothing to give the one behind.
876
- manager.viewers.of(base, "ahead").moveTo(100);
877
- manager.viewers.of(base, "ahead").playing = false;
878
- manager.viewers.of(base, "behind").moveTo(40);
879
- manager.viewers.of(base, "behind").playing = false;
880
- manager.getCachedAudioTracks = () => [
881
- { index: 0, language: "rus", title: "", isDefault: true },
882
- { index: 1, language: "eng", title: "", isDefault: false }
883
- ];
884
- const created = [];
885
- manager.viewerRequests.createOrGetSession = async (params) => {
886
- created.push(params);
887
- // The output itself, which is what `createOrGetSession` answers, carrying
888
- // the track it was asked for.
889
- return fakeSession({
890
- id: VARIANT_ID,
891
- encodeHeight: 0,
892
- dirPath,
893
- audioOnly: true,
894
- audioSourceTrackIndex: params.audioTrackIndex
895
- });
896
- };
897
-
898
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
899
-
900
- assert.equal(
901
- created[0].startPositionSeconds,
902
- 36,
903
- "the viewer at 40 s, less one segment of margin — a run starting at the leader " +
904
- "has nothing to give the one behind them"
905
- );
906
- });
907
-
908
- test("a soundtrack begins where a viewer says they are, whenever they said it", async (t) => {
909
- const { manager, base, dirPath } = await managerWithBase();
910
- t.after(async () => {
911
- await manager.lifecycle.disposeAll();
912
- await rm(dirPath, { recursive: true, force: true });
913
- });
914
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
915
- // TWO RULES WENT WHEN THE QUANTITY STOPPED MEANING TWO THINGS. A position
916
- // "past the read head" had to be clamped, because the read head was a
917
- // request edge and a report could overtake it; and a report older than a few
918
- // seconds had to be discarded, because it was being subtracted from that
919
- // edge. Neither survives: this is where the viewer's PICTURE is, they are the
920
- // only writer of it, and between statements it moves at the rate the film
921
- // moves. An old statement from a stopped viewer is exactly as true as a new
922
- // one.
923
- const viewer = manager.viewers.of(base, "viewer");
924
- viewer.moveTo(900, Date.now() - 600_000);
925
- viewer.playing = false;
926
- manager.getCachedAudioTracks = () => [
927
- { index: 0, language: "rus", title: "", isDefault: true },
928
- { index: 1, language: "eng", title: "", isDefault: false }
929
- ];
930
- const created = [];
931
- manager.viewerRequests.createOrGetSession = async (params) => {
932
- created.push(params);
933
- // The output itself, which is what `createOrGetSession` answers, carrying
934
- // the track it was asked for.
935
- return fakeSession({
936
- id: VARIANT_ID,
937
- encodeHeight: 0,
938
- dirPath,
939
- audioOnly: true,
940
- audioSourceTrackIndex: params.audioTrackIndex
941
- });
942
- };
943
-
944
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
945
-
946
- assert.equal(
947
- created[0].startPositionSeconds,
948
- 896,
949
- "ten minutes of silence from a stopped viewer says they are still at 900 s"
950
- );
951
- });
952
-
953
- test("an audio track is prepared at the position the switch will land on", async (t) => {
954
- const { manager, base, dirPath } = await managerWithBase();
955
- t.after(async () => {
956
- await manager.lifecycle.disposeAll();
957
- await rm(dirPath, { recursive: true, force: true });
958
- });
959
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
960
- manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
961
- manager.getCachedAudioTracks = () => [
962
- { index: 0, language: "rus", title: "", isDefault: true },
963
- { index: 1, language: "eng", title: "", isDefault: false }
964
- ];
965
- const rendition = fakeSession({
966
- id: VARIANT_ID,
967
- encodeHeight: 0,
968
- dirPath,
969
- audioOnly: true,
970
- audioSourceTrackIndex: 1
971
- });
972
- rendition.id = rendition.spec.toName();
973
- // A soundtrack of THIS picture: the same file, published on its own. Found by
974
- // what it is — there is no list of ids to put it on.
975
- rendition.file = base.file;
976
- startManagedRun(manager, rendition, { process: fakeEncoder() });
977
- manager.outputs.set(rendition.id, rendition);
978
-
979
- const prepared = await manager.renditions.prepareAudioTrack(BASE_ID, 1, 240, VIEWER);
980
-
981
- assert.deepEqual(
982
- prepared,
983
- { sessionId: rendition.id, fileName: "segment-00060.mp4" },
984
- "the caller is told which segment to wait for — 240 s on a four-second grid"
985
- );
986
- assert.equal(
987
- manager.viewers.of(rendition, VIEWER).positionSeconds(),
988
- 240,
989
- "and the track is told where this person is, which is what the switch will land on"
990
- );
991
- });
992
-
993
- test("a reading from a soundtrack is priced as one", () => {
994
- // The fault this pins: an audio rendition reached no learner at all. One
995
- // guard refused renditions a reading, and the only call that would have
996
- // priced one sat behind a second guard its caller had already made — so a
997
- // soundtrack ran for the whole film and was charged at nothing, which is the
998
- // half of roadmap item 6 that was left owing.
999
- assert.equal(costKindForSession({ spec: outputSpec({ audioOnly: true }) }), "audio");
1000
- assert.equal(
1001
- costKindForSession({ spec: outputSpec({ audioOnly: true, transcodeVideo: true }) }),
1002
- "audio",
1003
- "a rendition carries no picture, whatever the flag it inherited says"
1004
- );
1005
- assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: true }) }), "decode");
1006
- assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: false }) }), "copy");
1007
- });
1008
-
1009
- test("a quality step being warmed is not refused by its own cost", async (t) => {
1010
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "warm-cost-"));
1011
- // The addon host's own figures, so the arithmetic below is the field's and
1012
- // not an invention. Without a benchmark the check returns every height
1013
- // untouched and a test over it would pass while proving nothing.
1014
- const { manager } = managerWithOwnStore({
1015
- softwarePresetBenchmark: [
1016
- { preset: "fast", pixelsPerSec: 17.0e6 },
1017
- { preset: "ultrafast", pixelsPerSec: 67.5e6 }
1018
- ],
1019
- decodeCostModel: { pixelTerm: 0.007742, bitrateTerm: 0, constantTerm: 0 }
1020
- });
1021
- t.after(async () => {
1022
- await manager.lifecycle.disposeAll();
1023
- await rm(dirPath, { recursive: true, force: true });
1024
- });
1025
- // A copied 1080p picture, and a 240p step warmed beside it for a switch —
1026
- // which is what every quality change does, two encoders on purpose.
1027
- const base = fakeSession({ id: BASE_ID, encodeHeight: 0, dirPath, transcodeVideo: false });
1028
- base.variantHeight = 1080;
1029
- // What this source costs to decode comes from the file's own facts, stated in
1030
- // the fixture: 1080p24 at 8 Mbit/s, the field file. Without them nothing can
1031
- // be priced and every height comes back offerable for want of a measurement,
1032
- // which would make the assertion hold for the wrong reason.
1033
- assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
1034
- const warming = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
1035
- warming.variantHeight = 240;
1036
- // Two sessions of ONE file share its facts, which is the whole point of the
1037
- // file being an object: a step warmed beside the picture is not a second file.
1038
- warming.file = base.file;
1039
- chooseFor(manager, base, 240, warming.outputKey);
1040
- // A step of the picture: same file, and a height of its own.
1041
- // Running, and running well: it says of itself that it holds twice realtime,
1042
- // i.e. half a second of work per second of video.
1043
- startManagedRun(manager, warming, { process: fakeEncoder() });
1044
- qualityStateOf(warming).lastAloneSpeed = 2;
1045
- manager.outputs.set(BASE_ID, base);
1046
- manager.outputs.set(VARIANT_ID, warming);
1047
-
1048
- const offered = manager.quality.offeredHeights(base);
1049
-
1050
- assert.ok(
1051
- offered.includes(240),
1052
- "charged its own cost while being judged, the step the viewer just asked for is dropped from the " +
1053
- "offer by the act of warming it — and its next segment 404s on a stream that is playing"
1054
- );
1055
- });
1056
-
1057
- test("the master survives a live offer that has collapsed to one rung", async (t) => {
1058
- // The field case of 2026-08-18, in the smallest form that reproduces it: a
1059
- // host too slow for any re-encoded rung, and a swarm whose interruptions
1060
- // demand far more than realtime. The live offer then holds only the height an
1061
- // encoder is already producing — and until this test existed, that made
1062
- // `buildMasterPlaylist` answer null and the route answer 404 to a session
1063
- // that had just published the address.
1064
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-collapse-"));
1065
- const { manager } = managerWithOwnStore({
1066
- // A megapixel a second: every rung below the source costs more than the
1067
- // machine has.
1068
- softwarePresetBenchmark: [{ preset: "veryfast", pixelsPerSec: 1_000_000 }],
1069
- decodeCostModel: { pixelTerm: 0.01, bitrateTerm: 0, constantTerm: 0 }
1070
- });
1071
- const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
1072
- // A thicker source than the fixture's, stated as the file's own bitrate
1073
- // rather than as a cost object the file now derives.
1074
- base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 10_000 });
1075
- // What this file's own reader measured: a step must run at eight times
1076
- // realtime to survive this swarm.
1077
- manager.hostLoad.requiredSpeedFor = () => 8;
1078
- manager.outputs.set(BASE_ID, base);
1079
- t.after(async () => {
1080
- await manager.lifecycle.disposeAll();
1081
- await rm(dirPath, { recursive: true, force: true });
1082
- });
1083
-
1084
- assert.deepEqual(
1085
- manager.quality.offeredHeights(base),
1086
- [812],
1087
- "the live judgement is unchanged: nothing but the running height is worth offering"
1088
- );
1089
-
1090
- const master = manager.renditions.buildMasterPlaylist(BASE_ID);
1091
-
1092
- assert.ok(master, "the master is a published document, not a live figure");
1093
- const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
1094
- assert.deepEqual(
1095
- heights,
1096
- [1080, 812, 720, 540, 480, 360, 240],
1097
- "every rung that can be spliced onto this cut grid stays addressable"
1098
- );
1099
- });
1100
-
1101
- test("two heights that clamp onto one picture share a single encoder", async (t) => {
1102
- const { manager, base, dirPath } = await managerWithBase();
1103
- const spawnedDirs = [];
1104
- t.after(async () => {
1105
- await manager.lifecycle.disposeAll();
1106
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1107
- await rm(dirPath, { recursive: true, force: true });
1108
- });
1109
-
1110
- // A host that can hold exactly one rung. Whatever height is asked for, the
1111
- // clamp inside createOrGetSession lands the encode on 240p — which is what a
1112
- // CM4 did on 2026-08-28, turning a 360p and a 540p request into two more
1113
- // ffmpeg processes making the same 426x240 picture as the 240p one.
1114
- const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1115
- const created = [];
1116
- manager.viewerRequests.createOrGetSession = async (params) => {
1117
- const id = madeIds[created.length];
1118
- created.push(params);
1119
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-clamped-"));
1120
- spawnedDirs.push(variantDir);
1121
- const variant = fakeSession({ id, encodeHeight: 240, dirPath: variantDir });
1122
- manager.outputs.set(id, variant);
1123
- return variant;
1124
- };
1125
-
1126
- const asked360 = await askFor(manager, base, 360);
1127
- const asked540 = await askFor(manager, base, 540);
1128
-
1129
- assert.equal(asked360.id, VARIANT_ID, "the first request made the encoder");
1130
- assert.equal(
1131
- asked540.id,
1132
- VARIANT_ID,
1133
- "and the second is served by it, because it produces the very same picture"
1134
- );
1135
- assert.equal(
1136
- manager.outputs.has(SECOND_VARIANT_ID),
1137
- false,
1138
- "the duplicate was let go as soon as its size was known"
1139
- );
1140
- assert.equal(
1141
- chosenOutputOf(manager.viewers, VIEWER, 540),
1142
- manager.outputs.get(VARIANT_ID)?.outputKey,
1143
- "540p is recorded as answered by the output the machine can hold"
1144
- );
1145
-
1146
- const askedAgain = await askFor(manager, base, 540);
1147
-
1148
- assert.equal(askedAgain.id, VARIANT_ID);
1149
- assert.equal(created.length, 2, "the third request created nothing at all");
1150
- });
1151
-
1152
- test("rungs that really do differ keep their own encoders", async (t) => {
1153
- const { manager, base, dirPath } = await managerWithBase();
1154
- const spawnedDirs = [];
1155
- t.after(async () => {
1156
- await manager.lifecycle.disposeAll();
1157
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1158
- await rm(dirPath, { recursive: true, force: true });
1159
- });
1160
-
1161
- // A host with room: each request is encoded at the height it named, so
1162
- // nothing may be merged. The sharing above must not become "one encoder for
1163
- // every rung".
1164
- const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1165
- const created = [];
1166
- manager.viewerRequests.createOrGetSession = async (params) => {
1167
- const id = madeIds[created.length];
1168
- created.push(params);
1169
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-distinct-"));
1170
- spawnedDirs.push(variantDir);
1171
- const variant = fakeSession({ id, encodeHeight: params.targetHeight, dirPath: variantDir });
1172
- manager.outputs.set(id, variant);
1173
- return variant;
1174
- };
1175
-
1176
- const asked360 = await askFor(manager, base, 360);
1177
- const asked540 = await askFor(manager, base, 540);
1178
-
1179
- assert.equal(asked360.id, VARIANT_ID);
1180
- assert.equal(asked540.id, SECOND_VARIANT_ID, "two different pictures, two encoders");
1181
- assert.equal(chosenOutputOf(manager.viewers, VIEWER, 360), asked360.outputKey);
1182
- assert.equal(chosenOutputOf(manager.viewers, VIEWER, 540), asked540.outputKey);
1183
- });
1184
-
1185
- test("a rung is never served from the COPY, whatever height the copy happens to be", async (t) => {
1186
- const { manager, base, dirPath } = await managerWithBase();
1187
- const spawnedDirs = [];
1188
- t.after(async () => {
1189
- await manager.lifecycle.disposeAll();
1190
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1191
- await rm(dirPath, { recursive: true, force: true });
1192
- });
1193
-
1194
- // The base is a COPY at 240p — no encoder behind it, and it is the one rung
1195
- // this host can always serve. Handing it to a request for a re-encoded 360p
1196
- // would give away exactly that, and a viewer stranded on a rung the machine
1197
- // cannot hold would have nowhere left to return to.
1198
- base.transcodeVideo = false;
1199
- base.encodeHeight = 240;
1200
- base.variantHeight = 240;
1201
- const created = [];
1202
- manager.viewerRequests.createOrGetSession = async (params) => {
1203
- created.push(params);
1204
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-copy-"));
1205
- spawnedDirs.push(variantDir);
1206
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath: variantDir });
1207
- manager.outputs.set(VARIANT_ID, variant);
1208
- return variant;
1209
- };
1210
-
1211
- const asked = await askFor(manager, base, 360);
1212
-
1213
- assert.equal(asked.id, VARIANT_ID, "the re-encoded rung is its own session, not the copy");
1214
- });
1215
-
1216
- test("a file opened at a position starts its sound THERE, not a look-ahead earlier", async (t) => {
1217
- const { manager, base, dirPath } = await managerWithBase();
1218
- t.after(async () => {
1219
- await manager.lifecycle.disposeAll();
1220
- await rm(dirPath, { recursive: true, force: true });
1221
- });
1222
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
1223
- // The state at the instant a page is opened at a position: nothing seeked,
1224
- // no segment served, no report from anybody. The read head is then not a
1225
- // request edge — it is where the session was made — and a browser that has
1226
- // just opened holds no buffer at all.
1227
- base.lastRequestedSegment = null;
1228
- manager.viewers.of(base, VIEWER).moveTo(588);
1229
- manager.getCachedAudioTracks = () => [
1230
- { index: 0, language: "rus", title: "", isDefault: true },
1231
- { index: 1, language: "eng", title: "", isDefault: false }
1232
- ];
1233
- const created = [];
1234
- manager.viewerRequests.createOrGetSession = async (params) => {
1235
- created.push(params);
1236
- // The output itself, which is what `createOrGetSession` answers, carrying
1237
- // the track it was asked for.
1238
- return fakeSession({
1239
- id: VARIANT_ID,
1240
- encodeHeight: 0,
1241
- dirPath,
1242
- audioOnly: true,
1243
- audioSourceTrackIndex: params.audioTrackIndex
1244
- });
1245
- };
1246
-
1247
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
1248
-
1249
- // Field 2026-08-31: this answered 460 for a page opened at 588 — the whole
1250
- // 120 s look-ahead subtracted from a buffer that did not exist — and the
1251
- // segment the viewer needed took 38.8 s to appear against the picture's 8.4 s.
1252
- assert.equal(
1253
- created[0].startPositionSeconds,
1254
- 584,
1255
- "where the viewer opened, less one segment of margin, and nothing else"
1256
- );
1257
- });
1
+ /**
2
+ * @file Quality variants: the master playlist, and what happens when the viewer
3
+ * moves between rungs.
4
+ *
5
+ * What makes a mid-stream change of quality possible at all is that every
6
+ * variant is cut at the SAME times, so a segment produced by one encoder can be
7
+ * appended where another encoder's would have gone. The last test here pins
8
+ * that property at its source; the rest cover the wiring that a route reaches —
9
+ * a module test that imports a function directly cannot see a caller that never
10
+ * calls it (2.9.124).
11
+ */
12
+
13
+ import test from "node:test";
14
+ import { fakeProcess as fakeEncoder, startRunOn } from "./helpers/encode-run.js";
15
+ import assert from "node:assert/strict";
16
+ import { SourceFile } from "../services/media/SourceFile.js";
17
+ import { Timeline } from "../services/encode/output/Timeline.js";
18
+ import { mkdtemp, rm } from "node:fs/promises";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { costKindForSession } from "../services/encode/quality/EncodeCost.js";
22
+ import { managerWithOwnStore } from "./helpers/manager.js";
23
+ import { fmp4Format } from "../services/encode/segment-formats/fmp4.js";
24
+ import { computeCutGrid } from "../services/encode/output/cut-grid.js";
25
+ import { buildRunCommand, nearestKeyframeAtOrBefore } from "../services/encode/run-command.js";
26
+ import { Output } from "../services/encode/output/Output.js";
27
+ import { outputSpec } from "./helpers/output-spec.js";
28
+ import { qualityStateOf } from "../services/encode/quality/OutputQualityState.js";
29
+ import { chooseOutput, chosenOutputOf } from "../services/viewer/choices.js";
30
+
31
+ const BASE_ID = "aaaaaaaabbbbcccc";
32
+ const VARIANT_ID = "1111111122223333";
33
+ const SECOND_VARIANT_ID = "9999999988887777";
34
+ /** The one person these checks are about. Every viewer has a name. */
35
+ const VIEWER = "viewer";
36
+
37
+ /**
38
+ * The rule has chosen `key` for this viewer at this height. It used to be one
39
+ * record per file and height for everybody (`OutputCatalog.servedBy`); it is
40
+ * the viewer's own now (roadmap item 97, step 11), so the viewer is registered
41
+ * first — a choice kept for nobody is lost.
42
+ *
43
+ * @param {object} manager
44
+ * @param {object} base
45
+ * @param {number} height
46
+ * @param {string} key
47
+ * @returns {void}
48
+ */
49
+ function chooseFor(manager, base, height, key) {
50
+ manager.viewers.of(base, VIEWER);
51
+ chooseOutput(manager.viewers, VIEWER, height, key);
52
+ }
53
+
54
+ /**
55
+ * Ask for a height as the viewer does. A request naming nobody is refused.
56
+ *
57
+ * @param {object} manager
58
+ * @param {object} base
59
+ * @param {number} height
60
+ * @returns {Promise<object | null>}
61
+ */
62
+ function askFor(manager, base, height) {
63
+ manager.viewers.of(base, VIEWER);
64
+ return manager.renditions.resolveVariantSession(BASE_ID, height, -1, VIEWER);
65
+ }
66
+ const SEGMENT_SECONDS = 4;
67
+
68
+ /**
69
+ * A session shaped like a live one, without the ffmpeg run behind it.
70
+ *
71
+ * @param {{ id: string, encodeHeight: number, dirPath: string, transcodeVideo?: boolean, audioOnly?: boolean, audioSeparate?: boolean, audioSourceTrackIndex?: number }} params
72
+ * @returns {object}
73
+ */
74
+ function fakeSession({
75
+ id,
76
+ encodeHeight,
77
+ dirPath,
78
+ transcodeVideo = true,
79
+ audioOnly = false,
80
+ audioSeparate = false,
81
+ audioSourceTrackIndex = 0
82
+ }) {
83
+ return {
84
+ id,
85
+ get outputKey() { return this.spec.toKey(); },
86
+ spec: outputSpec({
87
+ transcodeVideo,
88
+ audioOnly,
89
+ audioSeparate,
90
+ audioSourceTrackIndex,
91
+ height: encodeHeight
92
+ }),
93
+ dirPath,
94
+ // Where this file is cut, held by the file. A fixture that stated it
95
+ // on the session was describing what production no longer does.
96
+ timeline: new Timeline({
97
+ boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
98
+ cutGrid: "uniform"
99
+ }),
100
+ state: "ready",
101
+ // The file's own facts, which is where the size and what decoding it costs
102
+ // both come from: 1080p24 at 8 Mbit/s, the field file of 2026-08-17. A
103
+ // fixture that assigned a cost object instead was stating an answer the
104
+ // file now derives, so nothing it said reached the arithmetic.
105
+ file: new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" }).learn({
106
+ width: 1920,
107
+ height: 1080,
108
+ fps: 24,
109
+ bitrateKbps: 8000
110
+ }),
111
+ // An ordinary session reads its own file, and its sound is inside it. The
112
+ // three differ only for a soundtrack shipped as a file of its own.
113
+ get inputFile() { return this.file; },
114
+ get audioFile() { return this.file; },
115
+ startedAt: Date.now(),
116
+ lastAccessedAt: Date.now(),
117
+ ffmpeg: null,
118
+ lastError: "",
119
+ segmentFormat: fmp4Format,
120
+ transcodeVideo,
121
+ transcodeAudio: true,
122
+ audioTrackIndex: 0,
123
+ // The shape this output is encoded AS, decided once for the output rather
124
+ // than once per session.
125
+ output: new Output({ encodeWidth: 0, encodeHeight, outputFps: 24, softwarePreset: null, applyTonemap: false }),
126
+ encodeRunGeneration: 0,
127
+ failedStartAt: -1,
128
+ failedStartCount: 0,
129
+ waitEpoch: 0,
130
+ usesExplicitCuts: false,
131
+ useSyntheticPlaylist: true,
132
+ playlistText: "#EXTM3U\n",
133
+ segmentCount: 100,
134
+ progress: { state: "running", processedSeconds: 0, startPositionSeconds: 0, speed: "1.0x" }
135
+ };
136
+ }
137
+
138
+
139
+ /**
140
+ * @returns {Promise<{ manager: object, base: object, dirPath: string }>}
141
+ */
142
+ async function managerWithBase() {
143
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-"));
144
+ // Its own store root — see `helpers/manager.js` for what sharing one cost.
145
+ const { manager } = managerWithOwnStore();
146
+ // 812p is what a viewport-sized budget actually produces — deliberately not a
147
+ // ladder rung, because that is the case the master has to carry.
148
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
149
+ manager.outputs.set(BASE_ID, base);
150
+ return { manager, base, dirPath };
151
+ }
152
+
153
+ function startManagedRun(manager, output, options = {}) {
154
+ const run = startRunOn(output, options);
155
+ manager.encodeOrchestrator.adopt(output.outputKey, run);
156
+ return run;
157
+ }
158
+
159
+ test("the master offers every rung, the session's own height among them", async (t) => {
160
+ const { manager, dirPath } = await managerWithBase();
161
+ t.after(async () => {
162
+ await manager.lifecycle.disposeAll();
163
+ await rm(dirPath, { recursive: true, force: true });
164
+ });
165
+
166
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID);
167
+
168
+ assert.ok(master, "a re-encoded 1080p source has rungs to choose between");
169
+ const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
170
+ assert.deepEqual(
171
+ heights,
172
+ [1080, 812, 720, 540, 480, 360, 240],
173
+ "the source height, the height already being encoded, and the rungs below it, largest first"
174
+ );
175
+ assert.match(master, /^#EXT-X-VERSION:7$/m, "the version the segment format requires");
176
+ assert.match(master, /RESOLUTION=1280x720/, "each variant states the size it decodes to");
177
+ assert.ok(
178
+ !master.includes("2160"),
179
+ "a rung above the source would be upscaling — invented detail at a higher cost than the source"
180
+ );
181
+ });
182
+
183
+ test("audio is published once for the file, and every rung points at it", async (t) => {
184
+ const { manager, base, dirPath } = await managerWithBase();
185
+ t.after(async () => {
186
+ await manager.lifecycle.disposeAll();
187
+ await rm(dirPath, { recursive: true, force: true });
188
+ });
189
+ // The inventory the plan already probed — the same list the browser's audio
190
+ // menu is built from.
191
+ manager.getCachedAudioTracks = () => [
192
+ { index: 0, language: "rus", title: "Дубляж", isDefault: true },
193
+ { index: 1, language: "eng", title: "", isDefault: false }
194
+ ];
195
+ // Settled at creation in production; set here directly, since this test
196
+ // builds its session by hand.
197
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
198
+ manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
199
+
200
+ // ASKED FOR BY THE VIEWER WHOSE CHOICE IT IS. Which soundtrack a master marks
201
+ // DEFAULT is a fact of the person the master is being built for — the route
202
+ // passes the name of whoever asked — so a nameless request is answered by the
203
+ // session's own parameters instead, which is another track entirely.
204
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID, VIEWER);
205
+
206
+ assert.match(
207
+ master,
208
+ /#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="Дубляж",LANGUAGE="ru",AUTOSELECT=YES,DEFAULT=NO,URI="a\/0\/index\.m3u8"/,
209
+ "a track with a title is named by it"
210
+ );
211
+ assert.match(
212
+ master,
213
+ /#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="eng",LANGUAGE="en",AUTOSELECT=YES,DEFAULT=YES,URI="a\/1\/index\.m3u8"/,
214
+ "the track the session was created with is the default one, and an untitled track is named by its language"
215
+ );
216
+ const streams = [...master.matchAll(/^#EXT-X-STREAM-INF:.*$/gm)].map((match) => match[0]);
217
+ assert.equal(streams.length, 7, "every rung");
218
+ assert.ok(
219
+ streams.every((line) => line.includes('AUDIO="aud"')),
220
+ "each rung plays with the shared audio rather than carrying its own"
221
+ );
222
+ });
223
+
224
+ test("a session that did not ask for renditions gets audio in its stream, as before", async (t) => {
225
+ const { manager, dirPath } = await managerWithBase();
226
+ t.after(async () => {
227
+ await manager.lifecycle.disposeAll();
228
+ await rm(dirPath, { recursive: true, force: true });
229
+ });
230
+ manager.getCachedAudioTracks = () => [{ index: 0, language: "rus", title: "", isDefault: true }];
231
+
232
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID);
233
+
234
+ assert.ok(!master.includes("EXT-X-MEDIA"), "a browser that does not know about renditions is not sent any");
235
+ assert.ok(!master.includes("AUDIO="), "and its rungs still carry their own audio");
236
+ });
237
+
238
+ test("a copied video is offered variants when its cut grid is real", async (t) => {
239
+ const { manager, base, dirPath } = await managerWithBase();
240
+ t.after(async () => {
241
+ await manager.lifecycle.disposeAll();
242
+ await rm(dirPath, { recursive: true, force: true });
243
+ });
244
+ // A copy is cut at the source's own keyframes — it has no other choice. A
245
+ // re-encoded rung CAN be cut there too, by being told those times, and then
246
+ // its segments cover the same spans and can stand in the copy's place.
247
+ base.spec = outputSpec({ transcodeVideo: false, cutGrid: "keyframe" });
248
+ base.timeline = new Timeline({ boundaries: base.timeline?.boundaries ?? [], cutGrid: "keyframe" });
249
+
250
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID);
251
+
252
+ assert.ok(master, "the obstacle was never the encoder, it was the cut points");
253
+ assert.match(master, /^v\/1080\/index\.m3u8$/m, "the copy itself is the top rung — no encoder, no cost");
254
+ assert.match(master, /^v\/540\/index\.m3u8$/m);
255
+ });
256
+
257
+ test("a copied video with no readable keyframe index is offered nothing", async (t) => {
258
+ const { manager, base, dirPath } = await managerWithBase();
259
+ t.after(async () => {
260
+ await manager.lifecycle.disposeAll();
261
+ await rm(dirPath, { recursive: true, force: true });
262
+ });
263
+ // Its playlist claims an even grid that ffmpeg does not cut on. Aligning a
264
+ // rung to that is aligning it to a fiction.
265
+ base.spec = outputSpec({ transcodeVideo: false, cutGrid: "uniform" });
266
+ base.timeline = new Timeline({ boundaries: base.timeline?.boundaries ?? [], cutGrid: "uniform" });
267
+
268
+ assert.equal(manager.renditions.buildMasterPlaylist(BASE_ID), null);
269
+ });
270
+
271
+ test("the session's own height resolves to the session itself", async (t) => {
272
+ const { manager, dirPath } = await managerWithBase();
273
+ t.after(async () => {
274
+ await manager.lifecycle.disposeAll();
275
+ await rm(dirPath, { recursive: true, force: true });
276
+ });
277
+
278
+ assert.deepEqual(
279
+ await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00000.mp4", VIEWER),
280
+ { sessionId: BASE_ID },
281
+ "an encoder is already producing this height; making a second one would be a cold start for nothing"
282
+ );
283
+ });
284
+
285
+ test("a height the master does not offer is refused", async (t) => {
286
+ const { manager, dirPath } = await managerWithBase();
287
+ t.after(async () => {
288
+ await manager.lifecycle.disposeAll();
289
+ await rm(dirPath, { recursive: true, force: true });
290
+ });
291
+
292
+ assert.deepEqual(
293
+ await manager.renditions.resolveVariantFile(BASE_ID, 999, "index.m3u8", VIEWER),
294
+ { sessionId: null },
295
+ "honouring an arbitrary height would let a client start encoder runs at will"
296
+ );
297
+ assert.deepEqual(
298
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "master.m3u8", VIEWER),
299
+ { sessionId: null },
300
+ "a master under a variant would describe variants of a variant"
301
+ );
302
+ });
303
+
304
+ test("a variant's playlist is answered without starting an encoder for it", async (t) => {
305
+ const { manager, dirPath } = await managerWithBase();
306
+ t.after(async () => {
307
+ await manager.lifecycle.disposeAll();
308
+ await rm(dirPath, { recursive: true, force: true });
309
+ });
310
+
311
+ const resolved = await manager.renditions.resolveVariantFile(BASE_ID, 540, "index.m3u8", VIEWER);
312
+
313
+ assert.deepEqual(
314
+ resolved,
315
+ { sessionId: BASE_ID },
316
+ "every variant of a file has the same media playlist — that is what makes them interchangeable"
317
+ );
318
+ assert.equal(
319
+ chosenOutputOf(manager.viewers, VIEWER, 540),
320
+ "",
321
+ "the player fetches a level's playlist to decide with, and may never switch to it"
322
+ );
323
+ });
324
+
325
+ test("the rung the page says it plays is the viewer's rung, and the encoder goes with it", async (t) => {
326
+ const { manager, base, dirPath } = await managerWithBase();
327
+ t.after(async () => {
328
+ await manager.lifecycle.disposeAll();
329
+ await rm(dirPath, { recursive: true, force: true });
330
+ });
331
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
332
+ variant.variantHeight = 540;
333
+ // A step of the picture: made as one, same file, and a height of its own.
334
+ variant.isStep = true;
335
+ manager.outputs.markStep(variant);
336
+ manager.outputs.set(VARIANT_ID, variant);
337
+ chooseFor(manager, base, 540, variant.outputKey);
338
+ // The viewer is a hundred seconds in, and the base is the one encoding.
339
+ base.lastRequestedSegment = 25;
340
+ const encoder = fakeEncoder();
341
+ startManagedRun(manager, base, { process: encoder });
342
+ manager.encodeRuns.planEncodersSoon = () => {};
343
+ const served = await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00025.mp4", VIEWER);
344
+ assert.equal(served.sessionId, VARIANT_ID, "the file must be served from the variant, not the base");
345
+ assert.equal(
346
+ manager.viewers.of(base, VIEWER).activeVariantId ?? null,
347
+ null,
348
+ "a request for a rung's segment is the player fetching, not the person having moved"
349
+ );
350
+
351
+ // The page, the moment the player has switched: this rung, and the picture at 100 s.
352
+ assert.equal(manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 100), true);
353
+
354
+ assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, VARIANT_ID, "the variant the viewer is watching is the active one");
355
+ assert.ok(
356
+ Math.abs((manager.viewers.of(variant, VIEWER).positionSeconds() ?? -1) - 100) < 1,
357
+ "where this person stands on the rung is where their picture is"
358
+ );
359
+ // AND THE RUNG THEY CAME OFF IS PRODUCING FOR NOBODY, which is one fact and
360
+ // not an act. It used to be stopped from this path by hand, and the plan —
361
+ // handed the whole film's priority map — started it again on the very next
362
+ // pass, which this viewer's own move had just triggered.
363
+ assert.equal(
364
+ manager.outputs.supersededBy(base, manager.viewers.of(base, VIEWER).activeVariantId),
365
+ true,
366
+ "the picture they stepped off is nobody's now"
367
+ );
368
+ assert.equal(
369
+ manager.outputs.supersededBy(variant, manager.viewers.of(variant, VIEWER).activeVariantId),
370
+ false,
371
+ "and the rung they moved to is theirs"
372
+ );
373
+ assert.deepEqual(encoder.signals, [], "stopping it is the plan's, from that fact, and not this path's");
374
+ });
375
+
376
+ test("a rung is placed where the picture is, not where the other rung had read to", async (t) => {
377
+ const { manager, base, dirPath } = await managerWithBase();
378
+ t.after(async () => {
379
+ await manager.lifecycle.disposeAll();
380
+ await rm(dirPath, { recursive: true, force: true });
381
+ });
382
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
383
+ variant.variantHeight = 540;
384
+ // A step of the picture: made as one, same file, and a height of its own.
385
+ variant.isStep = true;
386
+ manager.outputs.markStep(variant);
387
+ manager.outputs.set(VARIANT_ID, variant);
388
+ chooseFor(manager, base, 540, variant.outputKey);
389
+ startManagedRun(manager, base, { process: fakeEncoder() });
390
+ // The rung being left had read fourteen segments further than the picture had
391
+ // played — an encoder running at several times realtime fills the buffer far
392
+ // ahead. Measured 2026-08-11: 56 s of gap, and using the read head placed the
393
+ // new run past everything the player then asked for, which no request could
394
+ // ever be answered from.
395
+ base.lastRequestedSegment = 70;
396
+
397
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00056.mp4", VIEWER);
398
+ manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 224);
399
+
400
+ assert.equal(
401
+ manager.viewers.of(variant, VIEWER).positionSeconds(),
402
+ 224,
403
+ "where the page says the picture is — 224 s, segment 56 on a four-second grid — " +
404
+ "not the read head fourteen segments further on"
405
+ );
406
+ });
407
+
408
+ test("warming a rung prepares it without taking the encoder from the one on screen", async (t) => {
409
+ const { manager, base, dirPath } = await managerWithBase();
410
+ t.after(async () => {
411
+ await manager.lifecycle.disposeAll();
412
+ await rm(dirPath, { recursive: true, force: true });
413
+ });
414
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
415
+ variant.variantHeight = 540;
416
+ // A step of the picture: made as one, same file, and a height of its own.
417
+ variant.isStep = true;
418
+ manager.outputs.markStep(variant);
419
+ manager.outputs.set(VARIANT_ID, variant);
420
+ chooseFor(manager, base, 540, variant.outputKey);
421
+ const encoder = fakeEncoder();
422
+ startManagedRun(manager, base, { process: encoder });
423
+ manager.encodeRuns.planEncodersSoon = () => {};
424
+ const prepared = await manager.renditions.prepareVariant(BASE_ID, 540, 240, VIEWER);
425
+
426
+ assert.deepEqual(
427
+ prepared,
428
+ { sessionId: VARIANT_ID, fileName: "segment-00060.mp4" },
429
+ "the caller is told which segment to wait for — 240 s on a four-second grid"
430
+ );
431
+ assert.equal(
432
+ manager.viewers.of(variant, VIEWER).positionSeconds(),
433
+ 240,
434
+ "the rung being warmed is told where this person is, which is what buys it an encoder"
435
+ );
436
+ assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, null, "nothing has switched yet");
437
+ assert.equal([...base.runs][0]?.process, encoder, "the picture on screen keeps its encoder until the player actually moves");
438
+ assert.deepEqual(encoder.signals, [], "stopping it here is what would put the spinner back");
439
+ });
440
+
441
+ test("a rung warmed at the playhead survives the switch that lands just ahead of it", async (t) => {
442
+ const { manager, base, dirPath } = await managerWithBase();
443
+ t.after(async () => {
444
+ await manager.lifecycle.disposeAll();
445
+ await rm(dirPath, { recursive: true, force: true });
446
+ });
447
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
448
+ variant.variantHeight = 540;
449
+ // A step of the picture: made as one, same file, and a height of its own.
450
+ variant.isStep = true;
451
+ manager.outputs.markStep(variant);
452
+ manager.outputs.set(VARIANT_ID, variant);
453
+ chooseFor(manager, base, 540, variant.outputKey);
454
+ startManagedRun(manager, base, { process: fakeEncoder() });
455
+ // Warmed AT THE PLAYHEAD (240 s = segment #60), which is what the browser
456
+ // sends from server 0.10.0 onwards, and the run is alive and has produced a
457
+ // few segments past it.
458
+ await manager.renditions.prepareVariant(BASE_ID, 540, 240, VIEWER);
459
+
460
+ startManagedRun(manager, variant, { from: 59, process: fakeEncoder() });
461
+ variant.progress = { ...variant.progress, processedSeconds: 268 };
462
+ variant.seekTarget = null;
463
+ variant.seekSettleTimer = null;
464
+
465
+ // hls.js flushes from the fragment after the one holding
466
+ // `currentTime + fetchdelay`, so its first request for the new rung is the
467
+ // playhead plus up to one fragment — here #61 against a run that began at
468
+ // #59. Warming at the END OF THE BUFFER instead put the run tens of seconds
469
+ // AHEAD of this request, which the proxy then read as a seek backwards:
470
+ // measured 2026-08-14, that killed a run holding 21.8 s of encoded output.
471
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00061.mp4", VIEWER);
472
+ manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 244);
473
+
474
+ assert.equal(manager.viewers.of(base, VIEWER).activeVariantId, VARIANT_ID, "the viewer has moved to this rung");
475
+ assert.equal(
476
+ variant.seekTarget,
477
+ null,
478
+ "the request is inside the warmed run, so nothing is repositioned and the warm-up is kept"
479
+ );
480
+ assert.equal([...variant.runs][0].from, 59, "the run still begins where it was warmed");
481
+ });
482
+
483
+ test("a rung warmed PAST the switch is repositioned, which is what warming late costs", async (t) => {
484
+ const { manager, base, dirPath } = await managerWithBase();
485
+ t.after(async () => {
486
+ await manager.lifecycle.disposeAll();
487
+ await rm(dirPath, { recursive: true, force: true });
488
+ });
489
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
490
+ variant.variantHeight = 540;
491
+ // A step of the picture: made as one, same file, and a height of its own.
492
+ variant.isStep = true;
493
+ manager.outputs.markStep(variant);
494
+ manager.outputs.set(VARIANT_ID, variant);
495
+ chooseFor(manager, base, 540, variant.outputKey);
496
+ startManagedRun(manager, base, { process: fakeEncoder() });
497
+ // The same session, warmed where the BUFFER ended rather than where the
498
+ // picture was — 60 s further on, which is an ordinary cushion. This is what
499
+ // server 0.9.3 sent and 0.11.0 stopped sending.
500
+ await manager.renditions.prepareVariant(BASE_ID, 540, 300, VIEWER);
501
+ startManagedRun(manager, variant, { from: 74, process: fakeEncoder() });
502
+ variant.progress = { ...variant.progress, processedSeconds: 310 };
503
+
504
+ // hls.js still lands near the playhead, so the request is far BEHIND the
505
+ // warmed run: the proxy reads it as a seek backwards and starts again, and
506
+ // everything the warm-up produced is thrown away. Measured in the field
507
+ // 2026-08-14 as 21.8 s of encoded output destroyed by the act of using it.
508
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "segment-00061.mp4", VIEWER);
509
+ manager.renditions.viewerPlays(BASE_ID, VIEWER, 540, 244);
510
+
511
+ assert.equal(
512
+ manager.viewers.of(variant, VIEWER).positionSeconds(),
513
+ 244,
514
+ "where the picture is, not where the warm-up had run to"
515
+ );
516
+ });
517
+
518
+ test("the rung on screen fetching its own segments does not cancel a warm-up", async (t) => {
519
+ const { manager, base, dirPath } = await managerWithBase();
520
+ t.after(async () => {
521
+ await manager.lifecycle.disposeAll();
522
+ await rm(dirPath, { recursive: true, force: true });
523
+ });
524
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
525
+ variant.variantHeight = 540;
526
+ // A step of the picture: made as one, same file, and a height of its own.
527
+ variant.isStep = true;
528
+ manager.outputs.markStep(variant);
529
+ manager.outputs.set(VARIANT_ID, variant);
530
+ chooseFor(manager, base, 540, variant.outputKey);
531
+ const warmedEncoder = fakeEncoder();
532
+ startManagedRun(manager, variant, { process: warmedEncoder });
533
+ startManagedRun(manager, base, { process: fakeEncoder() });
534
+ manager.encodeRuns.planEncodersSoon = () => {};
535
+ await manager.renditions.prepareVariant(BASE_ID, 540, 100, VIEWER);
536
+
537
+ // The viewer has not moved: the rung they are watching goes on asking for its
538
+ // own segments, every few seconds, for as long as they watch.
539
+ await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00026.mp4", VIEWER);
540
+ manager.renditions.viewerPlays(BASE_ID, VIEWER, 812, 104);
541
+ await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00027.mp4", VIEWER);
542
+ manager.renditions.viewerPlays(BASE_ID, VIEWER, 812, 108);
543
+
544
+ // Kept per viewer.
545
+ assert.equal(
546
+ manager.viewers.forOutput(base).get(VIEWER)?.warmingVariantId ?? null,
547
+ VARIANT_ID,
548
+ "the rung being prepared is still being prepared"
549
+ );
550
+ assert.deepEqual(
551
+ warmedEncoder.signals,
552
+ [],
553
+ "cancelling it here left the viewer waiting out the whole warm-up for a segment nobody was making"
554
+ );
555
+ });
556
+
557
+ test("warming the height the base itself serves still points it at the switch", async (t) => {
558
+ const { manager, base, dirPath } = await managerWithBase();
559
+ t.after(async () => {
560
+ await manager.lifecycle.disposeAll();
561
+ await rm(dirPath, { recursive: true, force: true });
562
+ });
563
+ // The viewer is on another rung; the base is parked where they left it, with
564
+ // its encoder stopped. Warming its height must bring it back.
565
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
566
+ variant.variantHeight = 540;
567
+ manager.outputs.set(VARIANT_ID, variant);
568
+ chooseFor(manager, base, 540, variant.outputKey);
569
+ manager.viewers.of(base, VIEWER).activeVariantId = VARIANT_ID;
570
+ base.runs = new Set();
571
+
572
+ await manager.renditions.prepareVariant(BASE_ID, 812, 400, VIEWER);
573
+
574
+ // 400 s falls on the boundary between #99 and #100, and a run starts one
575
+ // segment back so the player has the preceding keyframe.
576
+ assert.equal(
577
+ manager.viewers.of(base, VIEWER).positionSeconds(),
578
+ 396,
579
+ "the base is parked where they left it, so warming its height says where they are like any other rung"
580
+ );
581
+ });
582
+
583
+ test("the viewer's position is kept current by the segments they ask for", async (t) => {
584
+ const { manager, base, dirPath } = await managerWithBase();
585
+ t.after(async () => {
586
+ await manager.lifecycle.disposeAll();
587
+ await rm(dirPath, { recursive: true, force: true });
588
+ });
589
+ // A REQUEST SAYS NOTHING ABOUT WHERE THEY ARE, and asking for one must not
590
+ // move them. Where they are is what they stated — a seek, or a report
591
+ // carrying their playhead — and it stands until they state otherwise.
592
+ manager.viewers.of(base, VIEWER).moveTo(40);
593
+
594
+ await manager.serving.getFileStream(BASE_ID, "segment-00090.mp4", { consumerId: VIEWER });
595
+
596
+ assert.ok(
597
+ Math.abs((manager.viewers.of(base, VIEWER).positionSeconds() ?? -1) - 40) < 1,
598
+ "a request for segment #90 leaves the viewer where they said they were"
599
+ );
600
+ });
601
+
602
+ test("a playlist or an init segment does not move the encoder", async (t) => {
603
+ const { manager, base, dirPath } = await managerWithBase();
604
+ t.after(async () => {
605
+ await manager.lifecycle.disposeAll();
606
+ await rm(dirPath, { recursive: true, force: true });
607
+ });
608
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 540, dirPath });
609
+ manager.outputs.set(VARIANT_ID, variant);
610
+ chooseFor(manager, base, 540, variant.outputKey);
611
+ startManagedRun(manager, base, { process: fakeEncoder() });
612
+ manager.encodeRuns.planEncodersSoon = () => {};
613
+ chooseFor(manager, base, 540, variant.outputKey);
614
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "index.m3u8", VIEWER);
615
+ await manager.renditions.resolveVariantFile(BASE_ID, 540, "init.mp4", VIEWER);
616
+
617
+ assert.notEqual(
618
+ manager.viewers.of(base, VIEWER).activeVariantId,
619
+ VARIANT_ID,
620
+ "hls.js fetches a level's playlist and init to decide with, and may never switch to it"
621
+ );
622
+ assert.ok([...base.runs][0]?.process, "the stream on screen must keep its encoder while the player is only looking");
623
+ });
624
+
625
+ test("the name of a variant is fixed, whatever its encode is later set to", async (t) => {
626
+ const { manager, base, dirPath } = await managerWithBase();
627
+ t.after(async () => {
628
+ await manager.lifecycle.disposeAll();
629
+ await rm(dirPath, { recursive: true, force: true });
630
+ });
631
+ // The player fetched the master once and addresses this variant as 812p for
632
+ // the rest of the session, so the name must not follow the encode. Nothing in
633
+ // the proxy changes `encodeHeight` mid-session any more — a change of size is
634
+ // a change of variant now — but the name and the encode are still two
635
+ // different things, and the addressing depends on their staying so.
636
+ assert.equal(manager.outputs.variantHeightOf(base), 812);
637
+ base.encodeHeight = 540;
638
+
639
+ assert.equal(
640
+ manager.outputs.variantHeightOf(base),
641
+ 812,
642
+ "the name stays; renaming it would leave the player addressing a variant nobody answers for"
643
+ );
644
+ assert.deepEqual(
645
+ await manager.renditions.resolveVariantFile(BASE_ID, 812, "segment-00000.mp4", VIEWER),
646
+ { sessionId: BASE_ID },
647
+ "a second session at a height the host has already failed to manage is the opposite of what a step is for"
648
+ );
649
+ });
650
+
651
+ test("the cut grid follows the grid asked for, not who produces the frames", () => {
652
+ // Why a segment from one encoder can stand where another's would have: both
653
+ // are cut at the same times. Which times is a property of the SESSION — the
654
+ // even grid, or the source's own keyframes — and it must not be re-derived
655
+ // from whether the video is copied, because a variant of a copied stream is
656
+ // re-encoded and still has to land on the copy's cuts.
657
+ const shape = { durationSeconds: 100, segDur: SEGMENT_SECONDS, startTime: 0 };
658
+ const keyframeTimes = [0, 3.1, 9.7, 14.2, 21.5, 40, 61.25];
659
+
660
+ const even = computeCutGrid({ ...shape, useKeyframeGrid: false, keyframeTimes });
661
+ assert.equal(even.boundaries[1], SEGMENT_SECONDS, "the even grid ignores the source's keyframes");
662
+ assert.equal(even.boundaries.at(-1), 100);
663
+
664
+ const source = computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes });
665
+ assert.deepEqual(
666
+ source.boundaries,
667
+ [0, 9.7, 14.2, 21.5, 40, 61.25, 100],
668
+ "the source's own keyframes, kept only where they are at least a segment apart"
669
+ );
670
+
671
+ // The one that matters: a copy and a re-encoded rung of it, given the same
672
+ // grid, produce the SAME table. Segment N then covers the same span in both,
673
+ // which is what lets one stand where the other would have.
674
+ assert.deepEqual(
675
+ computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes }).boundaries,
676
+ source.boundaries,
677
+ "a variant inherits the grid, so its boundaries are the same values"
678
+ );
679
+ // And with no index there is nothing to align to — the even grid, whoever asks.
680
+ assert.deepEqual(
681
+ computeCutGrid({ ...shape, useKeyframeGrid: true, keyframeTimes: null }).boundaries,
682
+ even.boundaries,
683
+ "no keyframes means no keyframe grid, however the caller asks"
684
+ );
685
+ });
686
+
687
+ test("a boundary carries the keyframe it is, exactly as the container stated it", () => {
688
+ // The fault that stopped a viewing on 2026-09-05. A boundary is kept on the
689
+ // player's clock, `keyframe - startTime`, rounded; the seek used to add the
690
+ // start time back and look the result up in the container's list by value.
691
+ // The round trip is lossy — 26.234 - 0.083 + 0.083 is 26.233999999999998 —
692
+ // and "the keyframe at or before that" is then the PREVIOUS one, a whole
693
+ // keyframe interval earlier.
694
+ const startTime = 0.083;
695
+ const keyframeTimes = [];
696
+ for (let index = 0; index < 60; index += 1) {
697
+ keyframeTimes.push(Number((startTime + index * 8.717).toFixed(3)));
698
+ }
699
+ const grid = computeCutGrid({
700
+ useKeyframeGrid: true, durationSeconds: 500, segDur: SEGMENT_SECONDS, keyframeTimes, startTime
701
+ });
702
+
703
+ assert.equal(grid.sourceTimes[0], startTime, "the first cut is the start of the file");
704
+ assert.equal(grid.boundaries.length, grid.sourceTimes.length, "an index must name both clocks");
705
+ for (let index = 1; index < grid.boundaries.length - 1; index += 1) {
706
+ assert.ok(
707
+ keyframeTimes.includes(grid.sourceTimes[index]),
708
+ `cut #${index} carries ${grid.sourceTimes[index]}, which the container never stated`
709
+ );
710
+ }
711
+
712
+ // What the round trip does, so the reason this table exists cannot be
713
+ // mistaken for caution: at least one boundary fails to find itself.
714
+ const lost = grid.boundaries
715
+ .slice(1, -1)
716
+ .filter((published, at) => nearestKeyframeAtOrBefore(keyframeTimes, published + startTime)
717
+ !== grid.sourceTimes[at + 1]);
718
+ assert.ok(
719
+ lost.length > 0,
720
+ "the search agreed everywhere, so this fixture no longer reproduces the fault it was built for"
721
+ );
722
+ });
723
+
724
+ test("a run on the keyframe grid is given no trim to apply", () => {
725
+ // The second half of the same fault. That trim is an output-side `-ss`, and
726
+ // beside `-copyts` it moves the whole run backwards by its own amount:
727
+ // measured 2026-09-06 on a 5 s keyframe interval, a run landing at 15 s and
728
+ // asked to trim to the cut at 20 s produced its first file starting at 10 s.
729
+ // Every cut of the run inherits it while the numbering, fixed at spawn, does
730
+ // not — so the files are named for times they do not hold.
731
+ const startTime = 0.083;
732
+ const keyframeTimes = [];
733
+ for (let index = 0; index < 60; index += 1) {
734
+ keyframeTimes.push(Number((startTime + index * 8.717).toFixed(3)));
735
+ }
736
+ const grid = computeCutGrid({
737
+ useKeyframeGrid: true, durationSeconds: 500, segDur: SEGMENT_SECONDS, keyframeTimes, startTime
738
+ });
739
+ const timeline = new Timeline({
740
+ boundaries: grid.boundaries, sourceTimes: grid.sourceTimes, cutGrid: "keyframe"
741
+ });
742
+
743
+ for (let index = 1; index < grid.boundaries.length - 1; index += 1) {
744
+ const { args } = buildRunCommand({
745
+ keyframes: { times: keyframeTimes },
746
+ inputFile: { startTime },
747
+ audioFile: { startTime },
748
+ inputUrl: "http://127.0.0.1/stream",
749
+ audioInputUrl: "",
750
+ outputDir: ".",
751
+ timeline,
752
+ segmentFormat: fmp4Format,
753
+ transcodeVideo: false,
754
+ transcodeAudio: true,
755
+ audioOnly: false,
756
+ audioSeparate: false,
757
+ audioSourceTrackIndex: 0,
758
+ rateControl: null,
759
+ startIndex: index,
760
+ endIndex: index,
761
+ videoEncoder: { name: "libx264" },
762
+ segmentDurationSec: SEGMENT_SECONDS
763
+ });
764
+ // One input seek establishes decode order in the preceding private cut.
765
+ assert.equal(
766
+ args.filter((one) => one === "-ss").length,
767
+ 1,
768
+ `run at #${index} was given a trim beside -copyts`
769
+ );
770
+ const seek = Number(args[args.indexOf("-ss") + 1]);
771
+ assert.ok(
772
+ Math.abs(seek - grid.sourceTimes[index - 1]) < 0.2,
773
+ `run at #${index} seeks to ${seek}, not to the preceding keyframe ${grid.sourceTimes[index - 1]}`
774
+ );
775
+ assert.equal(Number(args[args.indexOf("-segment_start_number") + 1]), index - 1);
776
+ }
777
+ });
778
+
779
+ test("a rung served by copy stays offered while a re-encoded rung is on screen", async (t) => {
780
+ const { manager, base, dirPath } = await managerWithBase();
781
+ t.after(async () => {
782
+ await manager.lifecycle.disposeAll();
783
+ await rm(dirPath, { recursive: true, force: true });
784
+ });
785
+ // The field case of 2026-08-15: a 1080p source served by COPY, the viewer on
786
+ // 240p, and a host too weak to re-encode anything above it.
787
+ base.spec = outputSpec({ transcodeVideo: false, cutGrid: "keyframe" });
788
+ base.encodeHeight = 1080;
789
+ base.variantHeight = 1080;
790
+ // Enough to re-encode 240p (1.67x combined) and nowhere near enough for
791
+ // 720p (0.45x) — the field's own shape, where the rung the viewer picked was
792
+ // offered and everything between it and the copy was not.
793
+ manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12_000_000 }];
794
+ manager.decodeCostModel = { pixelTerm: 0.00793, bitrateTerm: 0, constantTerm: 0 };
795
+ // What decoding this source costs comes from the file's own facts, stated in
796
+ // the fixture: 49.766 Mpx/s at 8 Mbit/s.
797
+ assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
798
+
799
+ const watching = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
800
+ watching.variantHeight = 240;
801
+ // The rung knows the source as well as the base does, because it IS the same
802
+ // file. Without that it prices nothing at all — every height comes back
803
+ // "sustainable" for want of a measurement — and the assertion below would
804
+ // hold for the wrong reason.
805
+ watching.file = base.file;
806
+ // A step of the picture: same file, and made as a step.
807
+ watching.isStep = true;
808
+ manager.outputs.markStep(watching);
809
+ manager.outputs.set(VARIANT_ID, watching);
810
+ chooseFor(manager, base, 240, watching.outputKey);
811
+ manager.viewers.of(base, VIEWER).activeVariantId = VARIANT_ID;
812
+
813
+ const offered = manager.quality.offeredHeights(watching);
814
+
815
+ assert.ok(
816
+ offered.includes(1080),
817
+ "the height the source is COPIED at costs no encoder, so no measurement of this host can withdraw it"
818
+ );
819
+ assert.deepEqual(
820
+ offered,
821
+ manager.quality.offeredHeights(base),
822
+ "one answer for the family: a rung asked while watching another must not disagree with the base"
823
+ );
824
+ });
825
+
826
+ test("a separately published audio track starts where the picture is, from the reported buffer", async (t) => {
827
+ const { manager, base, dirPath } = await managerWithBase();
828
+ t.after(async () => {
829
+ await manager.lifecycle.disposeAll();
830
+ await rm(dirPath, { recursive: true, force: true });
831
+ });
832
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
833
+ manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
834
+ // The viewer says where their picture is: 100 s. That, less a segment of
835
+ // margin, is where the track has to begin — no subtraction of anything,
836
+ // because the position is the playhead and not the edge of a buffer.
837
+ manager.viewers.of(base, "viewer").moveTo(100);
838
+ manager.viewers.of(base, "viewer").playing = false;
839
+ manager.getCachedAudioTracks = () => [
840
+ { index: 0, language: "rus", title: "", isDefault: true },
841
+ { index: 1, language: "eng", title: "", isDefault: false }
842
+ ];
843
+ const created = [];
844
+ manager.viewerRequests.createOrGetSession = async (params) => {
845
+ created.push(params);
846
+ // The output itself, which is what `createOrGetSession` answers, carrying
847
+ // the track it was asked for.
848
+ return fakeSession({
849
+ id: VARIANT_ID,
850
+ encodeHeight: 0,
851
+ dirPath,
852
+ audioOnly: true,
853
+ audioSourceTrackIndex: params.audioTrackIndex
854
+ });
855
+ };
856
+
857
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
858
+
859
+ assert.equal(created.length, 1, "the track's own session was made");
860
+ assert.equal(
861
+ created[0].startPositionSeconds,
862
+ 96,
863
+ "140 s served, less the 40 s the player holds, less one segment of margin"
864
+ );
865
+ });
866
+
867
+ test("with two viewers the audio track starts at the EARLIEST picture, not the read head", async (t) => {
868
+ const { manager, base, dirPath } = await managerWithBase();
869
+ t.after(async () => {
870
+ await manager.lifecycle.disposeAll();
871
+ await rm(dirPath, { recursive: true, force: true });
872
+ });
873
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
874
+ // A copied picture is one session shared by both of them, and a track begun
875
+ // at the leader has nothing to give the one behind.
876
+ manager.viewers.of(base, "ahead").moveTo(100);
877
+ manager.viewers.of(base, "ahead").playing = false;
878
+ manager.viewers.of(base, "behind").moveTo(40);
879
+ manager.viewers.of(base, "behind").playing = false;
880
+ manager.getCachedAudioTracks = () => [
881
+ { index: 0, language: "rus", title: "", isDefault: true },
882
+ { index: 1, language: "eng", title: "", isDefault: false }
883
+ ];
884
+ const created = [];
885
+ manager.viewerRequests.createOrGetSession = async (params) => {
886
+ created.push(params);
887
+ // The output itself, which is what `createOrGetSession` answers, carrying
888
+ // the track it was asked for.
889
+ return fakeSession({
890
+ id: VARIANT_ID,
891
+ encodeHeight: 0,
892
+ dirPath,
893
+ audioOnly: true,
894
+ audioSourceTrackIndex: params.audioTrackIndex
895
+ });
896
+ };
897
+
898
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
899
+
900
+ assert.equal(
901
+ created[0].startPositionSeconds,
902
+ 36,
903
+ "the viewer at 40 s, less one segment of margin — a run starting at the leader " +
904
+ "has nothing to give the one behind them"
905
+ );
906
+ });
907
+
908
+ test("a soundtrack begins where a viewer says they are, whenever they said it", async (t) => {
909
+ const { manager, base, dirPath } = await managerWithBase();
910
+ t.after(async () => {
911
+ await manager.lifecycle.disposeAll();
912
+ await rm(dirPath, { recursive: true, force: true });
913
+ });
914
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
915
+ // TWO RULES WENT WHEN THE QUANTITY STOPPED MEANING TWO THINGS. A position
916
+ // "past the read head" had to be clamped, because the read head was a
917
+ // request edge and a report could overtake it; and a report older than a few
918
+ // seconds had to be discarded, because it was being subtracted from that
919
+ // edge. Neither survives: this is where the viewer's PICTURE is, they are the
920
+ // only writer of it, and between statements it moves at the rate the film
921
+ // moves. An old statement from a stopped viewer is exactly as true as a new
922
+ // one.
923
+ const viewer = manager.viewers.of(base, "viewer");
924
+ viewer.moveTo(900, Date.now() - 600_000);
925
+ viewer.playing = false;
926
+ manager.getCachedAudioTracks = () => [
927
+ { index: 0, language: "rus", title: "", isDefault: true },
928
+ { index: 1, language: "eng", title: "", isDefault: false }
929
+ ];
930
+ const created = [];
931
+ manager.viewerRequests.createOrGetSession = async (params) => {
932
+ created.push(params);
933
+ // The output itself, which is what `createOrGetSession` answers, carrying
934
+ // the track it was asked for.
935
+ return fakeSession({
936
+ id: VARIANT_ID,
937
+ encodeHeight: 0,
938
+ dirPath,
939
+ audioOnly: true,
940
+ audioSourceTrackIndex: params.audioTrackIndex
941
+ });
942
+ };
943
+
944
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
945
+
946
+ assert.equal(
947
+ created[0].startPositionSeconds,
948
+ 896,
949
+ "ten minutes of silence from a stopped viewer says they are still at 900 s"
950
+ );
951
+ });
952
+
953
+ test("an audio track is prepared at the position the switch will land on", async (t) => {
954
+ const { manager, base, dirPath } = await managerWithBase();
955
+ t.after(async () => {
956
+ await manager.lifecycle.disposeAll();
957
+ await rm(dirPath, { recursive: true, force: true });
958
+ });
959
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
960
+ manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
961
+ manager.getCachedAudioTracks = () => [
962
+ { index: 0, language: "rus", title: "", isDefault: true },
963
+ { index: 1, language: "eng", title: "", isDefault: false }
964
+ ];
965
+ const rendition = fakeSession({
966
+ id: VARIANT_ID,
967
+ encodeHeight: 0,
968
+ dirPath,
969
+ audioOnly: true,
970
+ audioSourceTrackIndex: 1
971
+ });
972
+ rendition.id = rendition.spec.toName();
973
+ // A soundtrack of THIS picture: the same file, published on its own. Found by
974
+ // what it is — there is no list of ids to put it on.
975
+ rendition.file = base.file;
976
+ startManagedRun(manager, rendition, { process: fakeEncoder() });
977
+ manager.outputs.set(rendition.id, rendition);
978
+
979
+ const prepared = await manager.renditions.prepareAudioTrack(BASE_ID, 1, 240, VIEWER);
980
+
981
+ assert.deepEqual(
982
+ prepared,
983
+ { sessionId: rendition.id, fileName: "segment-00060.mp4" },
984
+ "the caller is told which segment to wait for — 240 s on a four-second grid"
985
+ );
986
+ assert.equal(
987
+ manager.viewers.of(rendition, VIEWER).positionSeconds(),
988
+ 240,
989
+ "and the track is told where this person is, which is what the switch will land on"
990
+ );
991
+ });
992
+
993
+ test("a reading from a soundtrack is priced as one", () => {
994
+ // The fault this pins: an audio rendition reached no learner at all. One
995
+ // guard refused renditions a reading, and the only call that would have
996
+ // priced one sat behind a second guard its caller had already made — so a
997
+ // soundtrack ran for the whole film and was charged at nothing, which is the
998
+ // half of roadmap item 6 that was left owing.
999
+ assert.equal(costKindForSession({ spec: outputSpec({ audioOnly: true }) }), "audio");
1000
+ assert.equal(
1001
+ costKindForSession({ spec: outputSpec({ audioOnly: true, transcodeVideo: true }) }),
1002
+ "audio",
1003
+ "a rendition carries no picture, whatever the flag it inherited says"
1004
+ );
1005
+ assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: true }) }), "decode");
1006
+ assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: false }) }), "copy");
1007
+ });
1008
+
1009
+ test("a quality step being warmed is not refused by its own cost", async (t) => {
1010
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "warm-cost-"));
1011
+ // The addon host's own figures, so the arithmetic below is the field's and
1012
+ // not an invention. Without a benchmark the check returns every height
1013
+ // untouched and a test over it would pass while proving nothing.
1014
+ const { manager } = managerWithOwnStore({
1015
+ softwarePresetBenchmark: [
1016
+ { preset: "fast", pixelsPerSec: 17.0e6 },
1017
+ { preset: "ultrafast", pixelsPerSec: 67.5e6 }
1018
+ ],
1019
+ decodeCostModel: { pixelTerm: 0.007742, bitrateTerm: 0, constantTerm: 0 }
1020
+ });
1021
+ t.after(async () => {
1022
+ await manager.lifecycle.disposeAll();
1023
+ await rm(dirPath, { recursive: true, force: true });
1024
+ });
1025
+ // A copied 1080p picture, and a 240p step warmed beside it for a switch —
1026
+ // which is what every quality change does, two encoders on purpose.
1027
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 0, dirPath, transcodeVideo: false });
1028
+ base.variantHeight = 1080;
1029
+ // What this source costs to decode comes from the file's own facts, stated in
1030
+ // the fixture: 1080p24 at 8 Mbit/s, the field file. Without them nothing can
1031
+ // be priced and every height comes back offerable for want of a measurement,
1032
+ // which would make the assertion hold for the wrong reason.
1033
+ assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
1034
+ const warming = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
1035
+ warming.variantHeight = 240;
1036
+ // Two sessions of ONE file share its facts, which is the whole point of the
1037
+ // file being an object: a step warmed beside the picture is not a second file.
1038
+ warming.file = base.file;
1039
+ chooseFor(manager, base, 240, warming.outputKey);
1040
+ // A step of the picture: same file, and a height of its own.
1041
+ // Running, and running well: it says of itself that it holds twice realtime,
1042
+ // i.e. half a second of work per second of video.
1043
+ startManagedRun(manager, warming, { process: fakeEncoder() });
1044
+ qualityStateOf(warming).lastAloneSpeed = 2;
1045
+ manager.outputs.set(BASE_ID, base);
1046
+ manager.outputs.set(VARIANT_ID, warming);
1047
+
1048
+ const offered = manager.quality.offeredHeights(base);
1049
+
1050
+ assert.ok(
1051
+ offered.includes(240),
1052
+ "charged its own cost while being judged, the step the viewer just asked for is dropped from the " +
1053
+ "offer by the act of warming it — and its next segment 404s on a stream that is playing"
1054
+ );
1055
+ });
1056
+
1057
+ test("the master survives a live offer that has collapsed to one rung", async (t) => {
1058
+ // The field case of 2026-08-18, in the smallest form that reproduces it: a
1059
+ // host too slow for any re-encoded rung, and a swarm whose interruptions
1060
+ // demand far more than realtime. The live offer then holds only the height an
1061
+ // encoder is already producing — and until this test existed, that made
1062
+ // `buildMasterPlaylist` answer null and the route answer 404 to a session
1063
+ // that had just published the address.
1064
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-collapse-"));
1065
+ const { manager } = managerWithOwnStore({
1066
+ // A megapixel a second: every rung below the source costs more than the
1067
+ // machine has.
1068
+ softwarePresetBenchmark: [{ preset: "veryfast", pixelsPerSec: 1_000_000 }],
1069
+ decodeCostModel: { pixelTerm: 0.01, bitrateTerm: 0, constantTerm: 0 }
1070
+ });
1071
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
1072
+ // A thicker source than the fixture's, stated as the file's own bitrate
1073
+ // rather than as a cost object the file now derives.
1074
+ base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 10_000 });
1075
+ // What this file's own reader measured: a step must run at eight times
1076
+ // realtime to survive this swarm.
1077
+ manager.hostLoad.requiredSpeedFor = () => 8;
1078
+ manager.outputs.set(BASE_ID, base);
1079
+ t.after(async () => {
1080
+ await manager.lifecycle.disposeAll();
1081
+ await rm(dirPath, { recursive: true, force: true });
1082
+ });
1083
+
1084
+ assert.deepEqual(
1085
+ manager.quality.offeredHeights(base),
1086
+ [812],
1087
+ "the live judgement is unchanged: nothing but the running height is worth offering"
1088
+ );
1089
+
1090
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID);
1091
+
1092
+ assert.ok(master, "the master is a published document, not a live figure");
1093
+ const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
1094
+ assert.deepEqual(
1095
+ heights,
1096
+ [1080, 812, 720, 540, 480, 360, 240],
1097
+ "every rung that can be spliced onto this cut grid stays addressable"
1098
+ );
1099
+ });
1100
+
1101
+ test("two heights that clamp onto one picture share a single encoder", async (t) => {
1102
+ const { manager, base, dirPath } = await managerWithBase();
1103
+ const spawnedDirs = [];
1104
+ t.after(async () => {
1105
+ await manager.lifecycle.disposeAll();
1106
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1107
+ await rm(dirPath, { recursive: true, force: true });
1108
+ });
1109
+
1110
+ // A host that can hold exactly one rung. Whatever height is asked for, the
1111
+ // clamp inside createOrGetSession lands the encode on 240p — which is what a
1112
+ // CM4 did on 2026-08-28, turning a 360p and a 540p request into two more
1113
+ // ffmpeg processes making the same 426x240 picture as the 240p one.
1114
+ const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1115
+ const created = [];
1116
+ manager.viewerRequests.createOrGetSession = async (params) => {
1117
+ const id = madeIds[created.length];
1118
+ created.push(params);
1119
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-clamped-"));
1120
+ spawnedDirs.push(variantDir);
1121
+ const variant = fakeSession({ id, encodeHeight: 240, dirPath: variantDir });
1122
+ manager.outputs.set(id, variant);
1123
+ return variant;
1124
+ };
1125
+
1126
+ const asked360 = await askFor(manager, base, 360);
1127
+ const asked540 = await askFor(manager, base, 540);
1128
+
1129
+ assert.equal(asked360.id, VARIANT_ID, "the first request made the encoder");
1130
+ assert.equal(
1131
+ asked540.id,
1132
+ VARIANT_ID,
1133
+ "and the second is served by it, because it produces the very same picture"
1134
+ );
1135
+ assert.equal(
1136
+ manager.outputs.has(SECOND_VARIANT_ID),
1137
+ false,
1138
+ "the duplicate was let go as soon as its size was known"
1139
+ );
1140
+ assert.equal(
1141
+ chosenOutputOf(manager.viewers, VIEWER, 540),
1142
+ manager.outputs.get(VARIANT_ID)?.outputKey,
1143
+ "540p is recorded as answered by the output the machine can hold"
1144
+ );
1145
+
1146
+ const askedAgain = await askFor(manager, base, 540);
1147
+
1148
+ assert.equal(askedAgain.id, VARIANT_ID);
1149
+ assert.equal(created.length, 2, "the third request created nothing at all");
1150
+ });
1151
+
1152
+ test("rungs that really do differ keep their own encoders", async (t) => {
1153
+ const { manager, base, dirPath } = await managerWithBase();
1154
+ const spawnedDirs = [];
1155
+ t.after(async () => {
1156
+ await manager.lifecycle.disposeAll();
1157
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1158
+ await rm(dirPath, { recursive: true, force: true });
1159
+ });
1160
+
1161
+ // A host with room: each request is encoded at the height it named, so
1162
+ // nothing may be merged. The sharing above must not become "one encoder for
1163
+ // every rung".
1164
+ const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1165
+ const created = [];
1166
+ manager.viewerRequests.createOrGetSession = async (params) => {
1167
+ const id = madeIds[created.length];
1168
+ created.push(params);
1169
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-distinct-"));
1170
+ spawnedDirs.push(variantDir);
1171
+ const variant = fakeSession({ id, encodeHeight: params.targetHeight, dirPath: variantDir });
1172
+ manager.outputs.set(id, variant);
1173
+ return variant;
1174
+ };
1175
+
1176
+ const asked360 = await askFor(manager, base, 360);
1177
+ const asked540 = await askFor(manager, base, 540);
1178
+
1179
+ assert.equal(asked360.id, VARIANT_ID);
1180
+ assert.equal(asked540.id, SECOND_VARIANT_ID, "two different pictures, two encoders");
1181
+ assert.equal(chosenOutputOf(manager.viewers, VIEWER, 360), asked360.outputKey);
1182
+ assert.equal(chosenOutputOf(manager.viewers, VIEWER, 540), asked540.outputKey);
1183
+ });
1184
+
1185
+ test("a rung is never served from the COPY, whatever height the copy happens to be", async (t) => {
1186
+ const { manager, base, dirPath } = await managerWithBase();
1187
+ const spawnedDirs = [];
1188
+ t.after(async () => {
1189
+ await manager.lifecycle.disposeAll();
1190
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1191
+ await rm(dirPath, { recursive: true, force: true });
1192
+ });
1193
+
1194
+ // The base is a COPY at 240p — no encoder behind it, and it is the one rung
1195
+ // this host can always serve. Handing it to a request for a re-encoded 360p
1196
+ // would give away exactly that, and a viewer stranded on a rung the machine
1197
+ // cannot hold would have nowhere left to return to.
1198
+ base.transcodeVideo = false;
1199
+ base.encodeHeight = 240;
1200
+ base.variantHeight = 240;
1201
+ const created = [];
1202
+ manager.viewerRequests.createOrGetSession = async (params) => {
1203
+ created.push(params);
1204
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-copy-"));
1205
+ spawnedDirs.push(variantDir);
1206
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath: variantDir });
1207
+ manager.outputs.set(VARIANT_ID, variant);
1208
+ return variant;
1209
+ };
1210
+
1211
+ const asked = await askFor(manager, base, 360);
1212
+
1213
+ assert.equal(asked.id, VARIANT_ID, "the re-encoded rung is its own session, not the copy");
1214
+ });
1215
+
1216
+ test("a file opened at a position starts its sound THERE, not a look-ahead earlier", async (t) => {
1217
+ const { manager, base, dirPath } = await managerWithBase();
1218
+ t.after(async () => {
1219
+ await manager.lifecycle.disposeAll();
1220
+ await rm(dirPath, { recursive: true, force: true });
1221
+ });
1222
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
1223
+ // The state at the instant a page is opened at a position: nothing seeked,
1224
+ // no segment served, no report from anybody. The read head is then not a
1225
+ // request edge — it is where the session was made — and a browser that has
1226
+ // just opened holds no buffer at all.
1227
+ base.lastRequestedSegment = null;
1228
+ manager.viewers.of(base, VIEWER).moveTo(588);
1229
+ manager.getCachedAudioTracks = () => [
1230
+ { index: 0, language: "rus", title: "", isDefault: true },
1231
+ { index: 1, language: "eng", title: "", isDefault: false }
1232
+ ];
1233
+ const created = [];
1234
+ manager.viewerRequests.createOrGetSession = async (params) => {
1235
+ created.push(params);
1236
+ // The output itself, which is what `createOrGetSession` answers, carrying
1237
+ // the track it was asked for.
1238
+ return fakeSession({
1239
+ id: VARIANT_ID,
1240
+ encodeHeight: 0,
1241
+ dirPath,
1242
+ audioOnly: true,
1243
+ audioSourceTrackIndex: params.audioTrackIndex
1244
+ });
1245
+ };
1246
+
1247
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
1248
+
1249
+ // Field 2026-08-31: this answered 460 for a page opened at 588 — the whole
1250
+ // 120 s look-ahead subtracted from a buffer that did not exist — and the
1251
+ // segment the viewer needed took 38.8 s to appear against the picture's 8.4 s.
1252
+ assert.equal(
1253
+ created[0].startPositionSeconds,
1254
+ 584,
1255
+ "where the viewer opened, less one segment of margin, and nothing else"
1256
+ );
1257
+ });