@torrent-tv/proxy 2.87.20 → 2.88.0

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 (474) hide show
  1. package/.claude/commands/opsx/apply.md +155 -155
  2. package/.claude/commands/opsx/archive.md +160 -160
  3. package/.claude/commands/opsx/explore.md +174 -174
  4. package/.claude/commands/opsx/propose.md +109 -109
  5. package/.claude/commands/opsx/sync.md +143 -143
  6. package/.claude/skills/openspec-apply-change/SKILL.md +159 -159
  7. package/.claude/skills/openspec-archive-change/SKILL.md +117 -117
  8. package/.claude/skills/openspec-explore/SKILL.md +289 -289
  9. package/.claude/skills/openspec-propose/SKILL.md +113 -113
  10. package/.claude/skills/openspec-sync-specs/SKILL.md +147 -147
  11. package/.dockerignore +5 -5
  12. package/AGENTS.md +322 -322
  13. package/CHANGELOG.md +8 -0
  14. package/Dockerfile +30 -30
  15. package/LICENSE +16 -16
  16. package/README.md +369 -369
  17. package/assets/calibration/NOTICE.md +100 -100
  18. package/assets/diagnostics/sctpstate.gdb +31 -31
  19. package/bin/cli.js +684 -684
  20. package/bin/thread-pool.js +30 -30
  21. package/biome.json +411 -411
  22. package/docs/browser-proxy-contract.md +133 -133
  23. package/docs/container-architecture.md +218 -218
  24. package/docs/download-architecture.md +261 -261
  25. package/docs/encode-architecture.md +729 -729
  26. package/docs/encode-run-state.md +96 -96
  27. package/docs/logs.md +97 -97
  28. package/docs/socks5-egress-research.md +114 -114
  29. package/docs/storage-architecture.md +267 -267
  30. package/knip.json +14 -14
  31. package/openspec/changes/adaptive-bitrate/design.md +92 -92
  32. package/openspec/changes/adaptive-bitrate/proposal.md +56 -56
  33. package/openspec/changes/adaptive-bitrate/specs/adaptive-bitrate/spec.md +51 -51
  34. package/openspec/changes/adaptive-bitrate/tasks.md +40 -40
  35. package/openspec/changes/binary-distribution/.openspec.yaml +2 -2
  36. package/openspec/changes/binary-distribution/proposal.md +53 -53
  37. package/openspec/changes/chunked-request-bodies/design.md +81 -81
  38. package/openspec/changes/chunked-request-bodies/proposal.md +53 -53
  39. package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -30
  40. package/openspec/changes/chunked-request-bodies/tasks.md +40 -40
  41. package/openspec/changes/cold-start/design.md +98 -98
  42. package/openspec/changes/cold-start/proposal.md +62 -62
  43. package/openspec/changes/cold-start/specs/cold-start/spec.md +47 -47
  44. package/openspec/changes/cold-start/tasks.md +48 -48
  45. package/openspec/changes/disk-cap/.openspec.yaml +2 -2
  46. package/openspec/changes/disk-cap/proposal.md +37 -37
  47. package/openspec/changes/disk-cap/specs/disk-cap/spec.md +25 -25
  48. package/openspec/changes/disk-cap/tasks.md +19 -19
  49. package/openspec/changes/proxy-observability/.openspec.yaml +2 -2
  50. package/openspec/changes/proxy-observability/design.md +38 -38
  51. package/openspec/changes/proxy-observability/proposal.md +49 -49
  52. package/openspec/changes/proxy-observability/specs/observability/spec.md +33 -33
  53. package/openspec/changes/proxy-observability/tasks.md +21 -21
  54. package/openspec/changes/seek-debounce/design.md +118 -118
  55. package/openspec/changes/seek-debounce/proposal.md +59 -59
  56. package/openspec/changes/seek-debounce/specs/seek-debounce/spec.md +41 -41
  57. package/openspec/changes/seek-debounce/tasks.md +33 -33
  58. package/openspec/changes/subtitle-language/.openspec.yaml +2 -2
  59. package/openspec/changes/subtitle-language/proposal.md +50 -50
  60. package/openspec/changes/subtitle-language/specs/subtitle-language/spec.md +34 -34
  61. package/openspec/changes/subtitle-language/tasks.md +26 -26
  62. package/openspec/changes/track-selection/.openspec.yaml +2 -2
  63. package/openspec/changes/track-selection/design.md +47 -47
  64. package/openspec/changes/track-selection/proposal.md +45 -45
  65. package/openspec/changes/track-selection/specs/track-selection/spec.md +41 -41
  66. package/openspec/changes/track-selection/tasks.md +20 -20
  67. package/openspec/changes/transcode-quality/.openspec.yaml +2 -2
  68. package/openspec/changes/transcode-quality/proposal.md +51 -51
  69. package/openspec/changes/transcode-quality/specs/transcode-quality/spec.md +139 -139
  70. package/openspec/changes/transcode-quality/tasks.md +63 -63
  71. package/openspec/config.yaml +38 -38
  72. package/package.json +50 -50
  73. package/public/.well-known/appspecific/com.chrome.devtools.json +1 -1
  74. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  75. package/research/double-spawn-2026-09-10.md +171 -171
  76. package/research/handover-2026-09-13.md +209 -209
  77. package/research/handover-reader-claims-removal-2026-09-12.md +166 -166
  78. package/research/piece-withdrawn-but-still-claimed-2026-09-12.md +175 -175
  79. package/research/preset-benchmark-size-scaling-2026-08-22.md +55 -55
  80. package/research/priority-map-is-the-truth-2026-09-12.md +225 -225
  81. package/routes/api/client-logs/post.js +86 -86
  82. package/routes/api/delivery-sink/get.js +72 -72
  83. package/routes/api/link-probe/get.js +51 -51
  84. package/routes/api/playback-plan/audio-tracks/post.js +29 -29
  85. package/routes/api/playback-plan/post.js +53 -53
  86. package/routes/api/sources/files/get.js +106 -100
  87. package/routes/api/sources/post.js +36 -36
  88. package/routes/api/sources/stats/get.js +132 -132
  89. package/routes/api/sources/warm/post.js +217 -217
  90. package/routes/api/subtitles/get.js +230 -230
  91. package/routes/api/transcode-sessions/fragment-far/post.js +60 -60
  92. package/routes/api/transcode-sessions/net-report/post.js +138 -138
  93. package/routes/api/transcode-sessions/post.js +173 -173
  94. package/routes/api/transcode-sessions/progress/get.js +27 -27
  95. package/routes/api/transcode-sessions/release/post.js +41 -41
  96. package/routes/api/transcode-sessions/seek/post.js +63 -63
  97. package/routes/health/get.js +13 -13
  98. package/routes/healthz/get.js +13 -13
  99. package/routes/stream/get.js +380 -380
  100. package/routes/transcode/audio-file/get.js +64 -64
  101. package/routes/transcode/audio-warm/get.js +84 -84
  102. package/routes/transcode/session-file/get.js +52 -52
  103. package/routes/transcode/variant-file/get.js +95 -95
  104. package/routes/transcode/variant-warm/get.js +84 -84
  105. package/scripts/render-run-graph.js +173 -173
  106. package/server.js +725 -725
  107. package/services/encode/CoverageMap.js +428 -428
  108. package/services/encode/CushionReport.js +345 -345
  109. package/services/encode/EncodeAdmission.js +376 -376
  110. package/services/encode/EncodeOrchestrator.js +1217 -1217
  111. package/services/encode/EncodePlan.js +1366 -1366
  112. package/services/encode/EncodeRun.js +813 -813
  113. package/services/encode/EncodeRuns.js +1235 -1235
  114. package/services/encode/Encoder.js +142 -142
  115. package/services/encode/EncoderSelection.js +38 -38
  116. package/services/encode/LocalObservations.js +359 -359
  117. package/services/encode/NvencEncoder.js +50 -50
  118. package/services/encode/OutputOpening.js +758 -758
  119. package/services/encode/OutputTimes.js +579 -579
  120. package/services/encode/QsvEncoder.js +58 -58
  121. package/services/encode/Renditions.js +2184 -2184
  122. package/services/encode/RunProgress.js +84 -84
  123. package/services/encode/SegmentDemand.js +95 -95
  124. package/services/encode/SoftwareEncoder.js +121 -121
  125. package/services/encode/V4l2m2mEncoder.js +53 -53
  126. package/services/encode/VaapiEncoder.js +66 -66
  127. package/services/encode/args.js +416 -416
  128. package/services/encode/available-share.js +89 -89
  129. package/services/encode/calibration.js +361 -361
  130. package/services/encode/contention.js +128 -128
  131. package/services/encode/decode-cost-fit.js +363 -363
  132. package/services/encode/encode-exit.js +114 -114
  133. package/services/encode/encode-run-state.js +551 -551
  134. package/services/encode/encoder-readings.js +45 -45
  135. package/services/encode/fingerprint.js +322 -322
  136. package/services/encode/host-load.js +174 -174
  137. package/services/encode/hwaccel.js +1894 -1894
  138. package/services/encode/index.js +9 -9
  139. package/services/encode/learned-median.js +90 -90
  140. package/services/encode/output/EncodedOutput.js +57 -57
  141. package/services/encode/output/Output.js +131 -131
  142. package/services/encode/output/OutputCatalog.js +414 -414
  143. package/services/encode/output/OutputSpec.js +390 -390
  144. package/services/encode/output/Timeline.js +308 -308
  145. package/services/encode/output/cut-grid.js +107 -107
  146. package/services/encode/output/index.js +20 -20
  147. package/services/encode/output/ladder.js +32 -32
  148. package/services/encode/output/playlists.js +284 -284
  149. package/services/encode/output/rates.js +125 -125
  150. package/services/encode/output-key-format.js +21 -21
  151. package/services/encode/quality/EncodeCost.js +1141 -1141
  152. package/services/encode/quality/HostLoad.js +525 -525
  153. package/services/encode/quality/HostTimings.js +249 -249
  154. package/services/encode/quality/OutputQualityState.js +28 -28
  155. package/services/encode/quality/QualityController.js +935 -935
  156. package/services/encode/quality/QualityOffer.js +416 -416
  157. package/services/encode/quality/drain-threat.js +47 -47
  158. package/services/encode/quality/link-budget.js +254 -254
  159. package/services/encode/quality/output-format.js +315 -315
  160. package/services/encode/quality/serving-output.js +216 -216
  161. package/services/encode/quality/visible-rung.js +57 -57
  162. package/services/encode/run-budget.js +97 -97
  163. package/services/encode/run-command.js +754 -754
  164. package/services/encode/run-costs.js +155 -155
  165. package/services/encode/run-inputs.js +42 -42
  166. package/services/encode/segment-formats/fmp4.js +456 -456
  167. package/services/encode/segment-formats/index.js +85 -85
  168. package/services/encode/segment-formats/init-compat.js +324 -324
  169. package/services/encode/segment-formats/mp4-boxes.js +515 -515
  170. package/services/encode/segment-formats/mpegts.js +134 -134
  171. package/services/encode/start-stop-cost.js +178 -178
  172. package/services/encode/throughput.js +97 -97
  173. package/services/encode/torrent-cost.js +88 -88
  174. package/services/identity/installation-id.js +38 -38
  175. package/services/media/ContainerOrchestrator.js +149 -149
  176. package/services/media/KeyframeTables.js +316 -316
  177. package/services/media/SourceFile.js +298 -298
  178. package/services/media/SubtitleCues.js +520 -520
  179. package/services/media/SubtitleOrchestrator.js +167 -167
  180. package/services/media/audio-inventory.js +245 -245
  181. package/services/media/container/AviContainer.js +266 -266
  182. package/services/media/container/Container.js +603 -603
  183. package/services/media/container/ContainerFactory.js +56 -56
  184. package/services/media/container/KeyframeTable.js +272 -272
  185. package/services/media/container/MatroskaContainer.js +1494 -1494
  186. package/services/media/container/Mp4Container.js +1244 -1244
  187. package/services/media/container/SubtitleFileContainer.js +322 -322
  188. package/services/media/container/ebml-reader.js +159 -159
  189. package/services/media/ffmpeg-banner.js +260 -260
  190. package/services/media/keyframe-probe.js +157 -157
  191. package/services/media/media-info-probe.js +93 -93
  192. package/services/media/playback-planner.js +931 -931
  193. package/services/media/tracks/AudioTrack.js +131 -131
  194. package/services/media/tracks/ContainerTrack.js +75 -75
  195. package/services/media/tracks/ImageSubtitleTrack.js +19 -19
  196. package/services/media/tracks/SubtitleTrack.js +38 -38
  197. package/services/media/tracks/TextSubtitleTrack.js +287 -287
  198. package/services/media/tracks/VideoTrack.js +33 -33
  199. package/services/media/tracks/index.js +15 -15
  200. package/services/media/tracks/language-detect.js +174 -174
  201. package/services/server/OutputLifecycle.js +418 -418
  202. package/services/server/SegmentServing.js +1150 -1150
  203. package/services/server/ViewerRequests.js +760 -760
  204. package/services/server/WaitLedger.js +142 -142
  205. package/services/server/controllers/PlaybackController.js +40 -40
  206. package/services/server/controllers/SubtitleController.js +109 -109
  207. package/services/server/http-responses.js +60 -60
  208. package/services/server/playback-readiness.js +696 -696
  209. package/services/server/transcode-session-files.js +325 -325
  210. package/services/server/wire-outputs.js +992 -992
  211. package/services/storage/Diagnostics.js +202 -202
  212. package/services/storage/MachineBudget.js +235 -235
  213. package/services/storage/allowance.js +107 -107
  214. package/services/storage/core-dumps.js +106 -106
  215. package/services/storage/files/CompletedFiles.js +391 -391
  216. package/services/storage/files/piece-from-whole-file.js +118 -118
  217. package/services/storage/free.js +71 -71
  218. package/services/storage/keep.js +48 -48
  219. package/services/storage/machine-memory.js +56 -56
  220. package/services/storage/memory-report.js +575 -575
  221. package/services/storage/piece-store/piece-disk-store.js +539 -539
  222. package/services/storage/piece-store/piece-lru.js +495 -495
  223. package/services/storage/piece-store/shared-piece-store.js +1931 -1908
  224. package/services/storage/returns.js +103 -103
  225. package/services/storage/segment-store/SegmentStore.js +1240 -1240
  226. package/services/storage/wire.js +175 -175
  227. package/services/torrent/Contents.js +382 -324
  228. package/services/torrent/demand/DemandRegister.js +202 -202
  229. package/services/torrent/demand/Urgency.js +137 -137
  230. package/services/torrent/demand/Window.js +118 -118
  231. package/services/torrent/demand/index.js +8 -8
  232. package/services/torrent/demand/pieces.js +140 -140
  233. package/services/torrent/download/SwarmSelection.js +386 -386
  234. package/services/torrent/download/registry.js +102 -102
  235. package/services/torrent/download/withdraw-claim.js +80 -80
  236. package/services/torrent/episode-naming.js +182 -0
  237. package/services/torrent/files.js +455 -455
  238. package/services/torrent/naming.js +619 -619
  239. package/services/torrent/piece-store-of.js +29 -29
  240. package/services/torrent/supply-margin.js +262 -262
  241. package/services/torrent/torrent-pool.js +2675 -2675
  242. package/services/torrent/worker/background-fill.js +213 -213
  243. package/services/torrent/worker/channel.js +271 -271
  244. package/services/torrent/worker/client.js +765 -765
  245. package/services/torrent/worker/fastest-wires.js +342 -342
  246. package/services/torrent/worker/handle-state.js +23 -23
  247. package/services/torrent/worker/held-bytes.js +155 -155
  248. package/services/torrent/worker/install-webrtc-shim.js +32 -32
  249. package/services/torrent/worker/piece-reader.js +1078 -1078
  250. package/services/torrent/worker/pool-adapter.js +371 -371
  251. package/services/torrent/worker/protocol.js +184 -184
  252. package/services/torrent/worker/resume-warm.js +107 -107
  253. package/services/torrent/worker/webrtc-shim.js +219 -219
  254. package/services/torrent/worker/worker.js +1129 -1129
  255. package/services/transport/data-channel-handler.js +1369 -1369
  256. package/services/transport/delivery-probe.js +842 -842
  257. package/services/transport/health-collector.js +53 -53
  258. package/services/transport/nat-classifier.js +231 -231
  259. package/services/transport/packet-witness.js +808 -808
  260. package/services/transport/port-mapper.js +235 -235
  261. package/services/transport/registry-api.js +81 -81
  262. package/services/transport/tunnel-client.js +447 -447
  263. package/services/transport/usrsctp-state.js +175 -175
  264. package/services/transport/webrtc-manager.js +484 -484
  265. package/services/viewer/Assignments.js +340 -340
  266. package/services/viewer/PriorityMap.js +390 -390
  267. package/services/viewer/PriorityOrchestrator.js +325 -325
  268. package/services/viewer/Viewer.js +691 -691
  269. package/services/viewer/Viewers.js +368 -368
  270. package/services/viewer/active-output.js +37 -37
  271. package/services/viewer/audio-start.js +46 -46
  272. package/services/viewer/buffer-trend.js +81 -81
  273. package/services/viewer/choices.js +647 -647
  274. package/services/viewer/positions.js +126 -126
  275. package/services/viewer/report-intake.js +46 -46
  276. package/store/source-registry.js +71 -71
  277. package/test/asset-paths.test.js +28 -28
  278. package/test/audio-inventory.test.js +212 -212
  279. package/test/audio-track-bitrate.test.js +40 -40
  280. package/test/auto-quality-step.test.js +707 -707
  281. package/test/available-share.test.js +76 -76
  282. package/test/background-fill.test.js +190 -190
  283. package/test/client-log-file.test.js +110 -110
  284. package/test/completed-files.test.js +115 -115
  285. package/test/concurrent-cost.test.js +148 -148
  286. package/test/container-media-info.test.js +228 -228
  287. package/test/contention.test.js +76 -76
  288. package/test/core-dumps.test.js +57 -57
  289. package/test/coverage-follows-the-disk.test.js +228 -228
  290. package/test/coverage-map.test.js +195 -195
  291. package/test/cue-push-carries-what-the-walk-found.test.js +58 -58
  292. package/test/cut-times-timeline.test.js +65 -65
  293. package/test/cuts-follow-published-grid.test.js +109 -109
  294. package/test/data-channel-frame.test.js +63 -63
  295. package/test/data-channel-viewer-lifecycle.test.js +92 -92
  296. package/test/dead-torrent-handle.test.js +52 -52
  297. package/test/declared-rates.test.js +116 -116
  298. package/test/declared-tracks.test.js +43 -43
  299. package/test/decode-cost-fit.test.js +202 -202
  300. package/test/decode-cost.test.js +462 -462
  301. package/test/delivery-probe.test.js +393 -393
  302. package/test/demand-register.test.js +206 -206
  303. package/test/dht-bootstrap.test.js +72 -72
  304. package/test/drain-threat.test.js +65 -65
  305. package/test/duplicate-add.test.js +48 -48
  306. package/test/encode-admission.test.js +146 -146
  307. package/test/encode-cost.test.js +283 -283
  308. package/test/encode-exit.test.js +111 -111
  309. package/test/encode-orchestrator.test.js +419 -419
  310. package/test/encode-plan-viewers.test.js +718 -718
  311. package/test/encode-plan.test.js +545 -545
  312. package/test/encode-run-state.test.js +314 -314
  313. package/test/encode-run.test.js +162 -162
  314. package/test/encode-slope.test.js +46 -46
  315. package/test/encoded-output.test.js +39 -39
  316. package/test/encoder-kinds.test.js +122 -122
  317. package/test/encoder-readings.test.js +46 -46
  318. package/test/episode-naming.test.js +131 -0
  319. package/test/every-claimant-is-told-its-share.test.js +152 -152
  320. package/test/failed-encoder-still-serves-what-exists.test.js +354 -354
  321. package/test/failed-start-breaker.test.js +202 -202
  322. package/test/fastest-wires.test.js +143 -143
  323. package/test/ffmpeg-stream-counts.test.js +78 -78
  324. package/test/file-edges.test.js +191 -191
  325. package/test/fmp4-presentation-clock.test.js +147 -147
  326. package/test/fmp4-self-contained.test.js +80 -80
  327. package/test/fmp4-timestamps.test.js +140 -140
  328. package/test/fmp4-track-completeness.test.js +41 -41
  329. package/test/format-keyed-outputs.test.js +78 -78
  330. package/test/health-metrics.test.js +38 -38
  331. package/test/held-request-width.test.js +157 -157
  332. package/test/helpers/encode-run.js +136 -136
  333. package/test/helpers/held-file.js +29 -29
  334. package/test/helpers/manager.js +57 -57
  335. package/test/helpers/output-spec.js +63 -63
  336. package/test/host-load.test.js +68 -68
  337. package/test/index-accuracy-is-about-the-file.test.js +128 -128
  338. package/test/init-compat.test.js +219 -219
  339. package/test/input-lost-quiets-the-plan.test.js +261 -261
  340. package/test/input-unavailable.test.js +48 -48
  341. package/test/installation-id.test.js +39 -39
  342. package/test/keeping-period.test.js +83 -83
  343. package/test/keyframe-index-accuracy.test.js +188 -188
  344. package/test/keyframe-table-budget.test.js +102 -102
  345. package/test/keyframes-belong-to-the-file.test.js +249 -249
  346. package/test/learned-median.test.js +37 -37
  347. package/test/letting-go-asks-who-is-watching.test.js +191 -191
  348. package/test/limit-row-by-area.test.js +60 -60
  349. package/test/link-budget.test.js +111 -111
  350. package/test/link-probe.test.js +56 -56
  351. package/test/local-encoding-data.test.js +273 -273
  352. package/test/logger-repeats.test.js +134 -134
  353. package/test/look-ahead-coverage.test.js +56 -56
  354. package/test/manager-surface.test.js +292 -292
  355. package/test/matroska-cues-track.test.js +192 -192
  356. package/test/memory-budget.test.js +390 -390
  357. package/test/move-cost.test.js +216 -216
  358. package/test/mp4-subtitles.test.js +173 -173
  359. package/test/one-authority.test.js +285 -285
  360. package/test/one-budget.test.js +149 -149
  361. package/test/one-output-one-session.test.js +204 -204
  362. package/test/one-resource-divided.test.js +185 -185
  363. package/test/one-serving-output-per-height.test.js +458 -458
  364. package/test/orchestrator-wired.test.js +206 -206
  365. package/test/output-catalog.test.js +39 -39
  366. package/test/output-shape.test.js +21 -21
  367. package/test/output-spec.test.js +251 -251
  368. package/test/output-speed.test.js +88 -88
  369. package/test/outputs-being-prepared.test.js +40 -40
  370. package/test/packet-witness-ring.test.js +236 -236
  371. package/test/packet-witness.test.js +148 -148
  372. package/test/piece-disk-store.test.js +401 -401
  373. package/test/piece-from-whole-file.test.js +129 -129
  374. package/test/piece-lru.test.js +319 -319
  375. package/test/piece-reader.test.js +162 -162
  376. package/test/piece-selection-offset.test.js +85 -85
  377. package/test/piece-store-eviction.test.js +595 -595
  378. package/test/piece-store-never-refuses.test.js +153 -153
  379. package/test/piece-store-reservations.test.js +403 -365
  380. package/test/piece-store-slow-disk.test.js +159 -159
  381. package/test/piece-tail.test.js +97 -97
  382. package/test/plan-host-timings.test.js +68 -68
  383. package/test/plan-is-steady.test.js +225 -225
  384. package/test/playback-readiness.test.js +453 -453
  385. package/test/playback-start-regressions.test.js +99 -99
  386. package/test/priority-map-download.test.js +174 -174
  387. package/test/priority-map-emptied.test.js +204 -204
  388. package/test/priority-map-per-output.test.js +215 -215
  389. package/test/priority-map.test.js +163 -163
  390. package/test/probe-wedge-certainty.test.js +60 -60
  391. package/test/produced-copy-choice.test.js +213 -213
  392. package/test/published-timeline.test.js +83 -83
  393. package/test/quality-offer.test.js +162 -162
  394. package/test/quality-variants.test.js +1229 -1229
  395. package/test/rate-control-in-the-output.test.js +180 -180
  396. package/test/read-survives-withdrawal.test.js +164 -164
  397. package/test/read-window.test.js +365 -365
  398. package/test/resume-warm.test.js +39 -39
  399. package/test/run-graph-drift.test.js +37 -37
  400. package/test/run-inputs.test.js +80 -80
  401. package/test/run-intervals.test.js +100 -100
  402. package/test/run-position-follows-published-grid.test.js +89 -89
  403. package/test/run-progress.test.js +65 -65
  404. package/test/same-height-switch.test.js +664 -664
  405. package/test/seek-frees-the-viewers-requests.test.js +217 -217
  406. package/test/seek-landing.test.js +109 -109
  407. package/test/seek-target-not-superseded.test.js +195 -195
  408. package/test/segment-closed-on-both-branches.test.js +96 -96
  409. package/test/segment-cut-times.test.js +63 -63
  410. package/test/segment-demand.test.js +80 -80
  411. package/test/segment-hold-supersede.test.js +91 -91
  412. package/test/segment-judged-by-its-own-header.test.js +221 -221
  413. package/test/segment-serve-wiring.test.js +475 -475
  414. package/test/segment-store-eviction.test.js +247 -247
  415. package/test/segment-store.test.js +323 -323
  416. package/test/segment-true-start.test.js +86 -86
  417. package/test/segments-are-shared.test.js +176 -176
  418. package/test/send-chunk-bytes.test.js +86 -86
  419. package/test/serving-existing-output.test.js +102 -102
  420. package/test/serving-output.test.js +102 -102
  421. package/test/shared-piece-store.test.js +310 -310
  422. package/test/sidecar-naming.test.js +142 -142
  423. package/test/source-file.test.js +133 -133
  424. package/test/source-files-route.test.js +12 -2
  425. package/test/source-registry.test.js +18 -18
  426. package/test/split-a-stretch.test.js +139 -139
  427. package/test/stale-request-after-seek.test.js +158 -158
  428. package/test/startup-readings.test.js +124 -124
  429. package/test/stream-route.test.js +209 -209
  430. package/test/subtitle-cue-framing.test.js +200 -200
  431. package/test/subtitle-cue-source.test.js +102 -102
  432. package/test/subtitle-cue-walk.test.js +370 -370
  433. package/test/subtitle-cursor.test.js +63 -63
  434. package/test/subtitle-defaults.test.js +118 -118
  435. package/test/subtitle-language.test.js +252 -252
  436. package/test/subtitle-track-numbering.test.js +386 -386
  437. package/test/supply-margin.test.js +177 -177
  438. package/test/swarm-follows-readers.test.js +174 -174
  439. package/test/swarm-reach.test.js +130 -130
  440. package/test/swarm-selection.test.js +220 -220
  441. package/test/tail-duplication.test.js +167 -167
  442. package/test/the-channel-has-both-ends.test.js +91 -91
  443. package/test/the-torrent-thread-serves-bytes.test.js +107 -107
  444. package/test/thread-pool.test.js +53 -53
  445. package/test/timeline.test.js +84 -84
  446. package/test/torrent-contents.test.js +235 -235
  447. package/test/torrent-cost.test.js +71 -71
  448. package/test/torrent-files.test.js +221 -221
  449. package/test/torrent-naming.test.js +255 -255
  450. package/test/tracks-begin-together.test.js +209 -209
  451. package/test/tunnel-renewal.test.js +167 -167
  452. package/test/two-viewers-one-picture.test.js +407 -407
  453. package/test/upload-hurry.test.js +186 -186
  454. package/test/usrsctp-state.test.js +131 -131
  455. package/test/video-facts.test.js +102 -102
  456. package/test/viewer-assignments.test.js +143 -143
  457. package/test/viewer-outputs.test.js +285 -285
  458. package/test/viewer-presence.test.js +116 -116
  459. package/test/viewer-requests-admission.test.js +89 -89
  460. package/test/viewer-states.test.js +189 -189
  461. package/test/viewer-subtitle-subscription.test.js +96 -96
  462. package/test/viewer.test.js +139 -139
  463. package/test/viewing-generations.test.js +390 -390
  464. package/test/visible-rung.test.js +37 -37
  465. package/test/wait-ledger.test.js +100 -100
  466. package/test/webrtc-shim.test.js +149 -149
  467. package/test/wedge-certainty.test.js +131 -131
  468. package/test/withdraw-piece-claim.test.js +212 -212
  469. package/test/worker-channel.test.js +158 -158
  470. package/utils/client-log-file.js +151 -151
  471. package/utils/logger.js +312 -312
  472. package/utils/parse-range.js +25 -25
  473. package/utils/perf.js +59 -59
  474. package/utils/torrent-source-key.js +38 -38
@@ -1,1229 +1,1229 @@
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
- const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
847
- return { sessionId: VARIANT_ID, session: rendition };
848
- };
849
-
850
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
851
-
852
- assert.equal(created.length, 1, "the track's own session was made");
853
- assert.equal(
854
- created[0].startPositionSeconds,
855
- 96,
856
- "140 s served, less the 40 s the player holds, less one segment of margin"
857
- );
858
- });
859
-
860
- test("with two viewers the audio track starts at the EARLIEST picture, not the read head", async (t) => {
861
- const { manager, base, dirPath } = await managerWithBase();
862
- t.after(async () => {
863
- await manager.lifecycle.disposeAll();
864
- await rm(dirPath, { recursive: true, force: true });
865
- });
866
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
867
- // A copied picture is one session shared by both of them, and a track begun
868
- // at the leader has nothing to give the one behind.
869
- manager.viewers.of(base, "ahead").moveTo(100);
870
- manager.viewers.of(base, "ahead").playing = false;
871
- manager.viewers.of(base, "behind").moveTo(40);
872
- manager.viewers.of(base, "behind").playing = false;
873
- manager.getCachedAudioTracks = () => [
874
- { index: 0, language: "rus", title: "", isDefault: true },
875
- { index: 1, language: "eng", title: "", isDefault: false }
876
- ];
877
- const created = [];
878
- manager.viewerRequests.createOrGetSession = async (params) => {
879
- created.push(params);
880
- const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
881
- return { sessionId: VARIANT_ID, session: rendition };
882
- };
883
-
884
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
885
-
886
- assert.equal(
887
- created[0].startPositionSeconds,
888
- 36,
889
- "the viewer at 40 s, less one segment of margin — a run starting at the leader " +
890
- "has nothing to give the one behind them"
891
- );
892
- });
893
-
894
- test("a soundtrack begins where a viewer says they are, whenever they said it", async (t) => {
895
- const { manager, base, dirPath } = await managerWithBase();
896
- t.after(async () => {
897
- await manager.lifecycle.disposeAll();
898
- await rm(dirPath, { recursive: true, force: true });
899
- });
900
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
901
- // TWO RULES WENT WHEN THE QUANTITY STOPPED MEANING TWO THINGS. A position
902
- // "past the read head" had to be clamped, because the read head was a
903
- // request edge and a report could overtake it; and a report older than a few
904
- // seconds had to be discarded, because it was being subtracted from that
905
- // edge. Neither survives: this is where the viewer's PICTURE is, they are the
906
- // only writer of it, and between statements it moves at the rate the film
907
- // moves. An old statement from a stopped viewer is exactly as true as a new
908
- // one.
909
- const viewer = manager.viewers.of(base, "viewer");
910
- viewer.moveTo(900, Date.now() - 600_000);
911
- viewer.playing = false;
912
- manager.getCachedAudioTracks = () => [
913
- { index: 0, language: "rus", title: "", isDefault: true },
914
- { index: 1, language: "eng", title: "", isDefault: false }
915
- ];
916
- const created = [];
917
- manager.viewerRequests.createOrGetSession = async (params) => {
918
- created.push(params);
919
- const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
920
- return { sessionId: VARIANT_ID, session: rendition };
921
- };
922
-
923
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
924
-
925
- assert.equal(
926
- created[0].startPositionSeconds,
927
- 896,
928
- "ten minutes of silence from a stopped viewer says they are still at 900 s"
929
- );
930
- });
931
-
932
- test("an audio track is prepared at the position the switch will land on", async (t) => {
933
- const { manager, base, dirPath } = await managerWithBase();
934
- t.after(async () => {
935
- await manager.lifecycle.disposeAll();
936
- await rm(dirPath, { recursive: true, force: true });
937
- });
938
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
939
- manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
940
- manager.getCachedAudioTracks = () => [
941
- { index: 0, language: "rus", title: "", isDefault: true },
942
- { index: 1, language: "eng", title: "", isDefault: false }
943
- ];
944
- const rendition = fakeSession({
945
- id: VARIANT_ID,
946
- encodeHeight: 0,
947
- dirPath,
948
- audioOnly: true,
949
- audioSourceTrackIndex: 1
950
- });
951
- rendition.id = rendition.spec.toName();
952
- // A soundtrack of THIS picture: the same file, published on its own. Found by
953
- // what it is — there is no list of ids to put it on.
954
- rendition.file = base.file;
955
- startManagedRun(manager, rendition, { process: fakeEncoder() });
956
- manager.outputs.set(rendition.id, rendition);
957
-
958
- const prepared = await manager.renditions.prepareAudioTrack(BASE_ID, 1, 240, VIEWER);
959
-
960
- assert.deepEqual(
961
- prepared,
962
- { sessionId: rendition.id, fileName: "segment-00060.mp4" },
963
- "the caller is told which segment to wait for — 240 s on a four-second grid"
964
- );
965
- assert.equal(
966
- manager.viewers.of(rendition, VIEWER).positionSeconds(),
967
- 240,
968
- "and the track is told where this person is, which is what the switch will land on"
969
- );
970
- });
971
-
972
- test("a reading from a soundtrack is priced as one", () => {
973
- // The fault this pins: an audio rendition reached no learner at all. One
974
- // guard refused renditions a reading, and the only call that would have
975
- // priced one sat behind a second guard its caller had already made — so a
976
- // soundtrack ran for the whole film and was charged at nothing, which is the
977
- // half of roadmap item 6 that was left owing.
978
- assert.equal(costKindForSession({ spec: outputSpec({ audioOnly: true }) }), "audio");
979
- assert.equal(
980
- costKindForSession({ spec: outputSpec({ audioOnly: true, transcodeVideo: true }) }),
981
- "audio",
982
- "a rendition carries no picture, whatever the flag it inherited says"
983
- );
984
- assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: true }) }), "decode");
985
- assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: false }) }), "copy");
986
- });
987
-
988
- test("a quality step being warmed is not refused by its own cost", async (t) => {
989
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "warm-cost-"));
990
- // The addon host's own figures, so the arithmetic below is the field's and
991
- // not an invention. Without a benchmark the check returns every height
992
- // untouched and a test over it would pass while proving nothing.
993
- const { manager } = managerWithOwnStore({
994
- softwarePresetBenchmark: [
995
- { preset: "fast", pixelsPerSec: 17.0e6 },
996
- { preset: "ultrafast", pixelsPerSec: 67.5e6 }
997
- ],
998
- decodeCostModel: { pixelTerm: 0.007742, bitrateTerm: 0, constantTerm: 0 }
999
- });
1000
- t.after(async () => {
1001
- await manager.lifecycle.disposeAll();
1002
- await rm(dirPath, { recursive: true, force: true });
1003
- });
1004
- // A copied 1080p picture, and a 240p step warmed beside it for a switch —
1005
- // which is what every quality change does, two encoders on purpose.
1006
- const base = fakeSession({ id: BASE_ID, encodeHeight: 0, dirPath, transcodeVideo: false });
1007
- base.variantHeight = 1080;
1008
- // What this source costs to decode comes from the file's own facts, stated in
1009
- // the fixture: 1080p24 at 8 Mbit/s, the field file. Without them nothing can
1010
- // be priced and every height comes back offerable for want of a measurement,
1011
- // which would make the assertion hold for the wrong reason.
1012
- assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
1013
- const warming = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
1014
- warming.variantHeight = 240;
1015
- // Two sessions of ONE file share its facts, which is the whole point of the
1016
- // file being an object: a step warmed beside the picture is not a second file.
1017
- warming.file = base.file;
1018
- chooseFor(manager, base, 240, warming.outputKey);
1019
- // A step of the picture: same file, and a height of its own.
1020
- // Running, and running well: it says of itself that it holds twice realtime,
1021
- // i.e. half a second of work per second of video.
1022
- startManagedRun(manager, warming, { process: fakeEncoder() });
1023
- qualityStateOf(warming).lastAloneSpeed = 2;
1024
- manager.outputs.set(BASE_ID, base);
1025
- manager.outputs.set(VARIANT_ID, warming);
1026
-
1027
- const offered = manager.quality.offeredHeights(base);
1028
-
1029
- assert.ok(
1030
- offered.includes(240),
1031
- "charged its own cost while being judged, the step the viewer just asked for is dropped from the " +
1032
- "offer by the act of warming it — and its next segment 404s on a stream that is playing"
1033
- );
1034
- });
1035
-
1036
- test("the master survives a live offer that has collapsed to one rung", async (t) => {
1037
- // The field case of 2026-08-18, in the smallest form that reproduces it: a
1038
- // host too slow for any re-encoded rung, and a swarm whose interruptions
1039
- // demand far more than realtime. The live offer then holds only the height an
1040
- // encoder is already producing — and until this test existed, that made
1041
- // `buildMasterPlaylist` answer null and the route answer 404 to a session
1042
- // that had just published the address.
1043
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-collapse-"));
1044
- const { manager } = managerWithOwnStore({
1045
- // A megapixel a second: every rung below the source costs more than the
1046
- // machine has.
1047
- softwarePresetBenchmark: [{ preset: "veryfast", pixelsPerSec: 1_000_000 }],
1048
- decodeCostModel: { pixelTerm: 0.01, bitrateTerm: 0, constantTerm: 0 }
1049
- });
1050
- const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
1051
- // A thicker source than the fixture's, stated as the file's own bitrate
1052
- // rather than as a cost object the file now derives.
1053
- base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 10_000 });
1054
- // What this file's own reader measured: a step must run at eight times
1055
- // realtime to survive this swarm.
1056
- manager.hostLoad.requiredSpeedFor = () => 8;
1057
- manager.outputs.set(BASE_ID, base);
1058
- t.after(async () => {
1059
- await manager.lifecycle.disposeAll();
1060
- await rm(dirPath, { recursive: true, force: true });
1061
- });
1062
-
1063
- assert.deepEqual(
1064
- manager.quality.offeredHeights(base),
1065
- [812],
1066
- "the live judgement is unchanged: nothing but the running height is worth offering"
1067
- );
1068
-
1069
- const master = manager.renditions.buildMasterPlaylist(BASE_ID);
1070
-
1071
- assert.ok(master, "the master is a published document, not a live figure");
1072
- const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
1073
- assert.deepEqual(
1074
- heights,
1075
- [1080, 812, 720, 540, 480, 360, 240],
1076
- "every rung that can be spliced onto this cut grid stays addressable"
1077
- );
1078
- });
1079
-
1080
- test("two heights that clamp onto one picture share a single encoder", async (t) => {
1081
- const { manager, base, dirPath } = await managerWithBase();
1082
- const spawnedDirs = [];
1083
- t.after(async () => {
1084
- await manager.lifecycle.disposeAll();
1085
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1086
- await rm(dirPath, { recursive: true, force: true });
1087
- });
1088
-
1089
- // A host that can hold exactly one rung. Whatever height is asked for, the
1090
- // clamp inside createOrGetSession lands the encode on 240p — which is what a
1091
- // CM4 did on 2026-08-28, turning a 360p and a 540p request into two more
1092
- // ffmpeg processes making the same 426x240 picture as the 240p one.
1093
- const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1094
- const created = [];
1095
- manager.viewerRequests.createOrGetSession = async (params) => {
1096
- const id = madeIds[created.length];
1097
- created.push(params);
1098
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-clamped-"));
1099
- spawnedDirs.push(variantDir);
1100
- const variant = fakeSession({ id, encodeHeight: 240, dirPath: variantDir });
1101
- manager.outputs.set(id, variant);
1102
- return variant;
1103
- };
1104
-
1105
- const asked360 = await askFor(manager, base, 360);
1106
- const asked540 = await askFor(manager, base, 540);
1107
-
1108
- assert.equal(asked360.id, VARIANT_ID, "the first request made the encoder");
1109
- assert.equal(
1110
- asked540.id,
1111
- VARIANT_ID,
1112
- "and the second is served by it, because it produces the very same picture"
1113
- );
1114
- assert.equal(
1115
- manager.outputs.has(SECOND_VARIANT_ID),
1116
- false,
1117
- "the duplicate was let go as soon as its size was known"
1118
- );
1119
- assert.equal(
1120
- chosenOutputOf(manager.viewers, VIEWER, 540),
1121
- manager.outputs.get(VARIANT_ID)?.outputKey,
1122
- "540p is recorded as answered by the output the machine can hold"
1123
- );
1124
-
1125
- const askedAgain = await askFor(manager, base, 540);
1126
-
1127
- assert.equal(askedAgain.id, VARIANT_ID);
1128
- assert.equal(created.length, 2, "the third request created nothing at all");
1129
- });
1130
-
1131
- test("rungs that really do differ keep their own encoders", async (t) => {
1132
- const { manager, base, dirPath } = await managerWithBase();
1133
- const spawnedDirs = [];
1134
- t.after(async () => {
1135
- await manager.lifecycle.disposeAll();
1136
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1137
- await rm(dirPath, { recursive: true, force: true });
1138
- });
1139
-
1140
- // A host with room: each request is encoded at the height it named, so
1141
- // nothing may be merged. The sharing above must not become "one encoder for
1142
- // every rung".
1143
- const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1144
- const created = [];
1145
- manager.viewerRequests.createOrGetSession = async (params) => {
1146
- const id = madeIds[created.length];
1147
- created.push(params);
1148
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-distinct-"));
1149
- spawnedDirs.push(variantDir);
1150
- const variant = fakeSession({ id, encodeHeight: params.targetHeight, dirPath: variantDir });
1151
- manager.outputs.set(id, variant);
1152
- return variant;
1153
- };
1154
-
1155
- const asked360 = await askFor(manager, base, 360);
1156
- const asked540 = await askFor(manager, base, 540);
1157
-
1158
- assert.equal(asked360.id, VARIANT_ID);
1159
- assert.equal(asked540.id, SECOND_VARIANT_ID, "two different pictures, two encoders");
1160
- assert.equal(chosenOutputOf(manager.viewers, VIEWER, 360), asked360.outputKey);
1161
- assert.equal(chosenOutputOf(manager.viewers, VIEWER, 540), asked540.outputKey);
1162
- });
1163
-
1164
- test("a rung is never served from the COPY, whatever height the copy happens to be", async (t) => {
1165
- const { manager, base, dirPath } = await managerWithBase();
1166
- const spawnedDirs = [];
1167
- t.after(async () => {
1168
- await manager.lifecycle.disposeAll();
1169
- await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1170
- await rm(dirPath, { recursive: true, force: true });
1171
- });
1172
-
1173
- // The base is a COPY at 240p — no encoder behind it, and it is the one rung
1174
- // this host can always serve. Handing it to a request for a re-encoded 360p
1175
- // would give away exactly that, and a viewer stranded on a rung the machine
1176
- // cannot hold would have nowhere left to return to.
1177
- base.transcodeVideo = false;
1178
- base.encodeHeight = 240;
1179
- base.variantHeight = 240;
1180
- const created = [];
1181
- manager.viewerRequests.createOrGetSession = async (params) => {
1182
- created.push(params);
1183
- const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-copy-"));
1184
- spawnedDirs.push(variantDir);
1185
- const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath: variantDir });
1186
- manager.outputs.set(VARIANT_ID, variant);
1187
- return variant;
1188
- };
1189
-
1190
- const asked = await askFor(manager, base, 360);
1191
-
1192
- assert.equal(asked.id, VARIANT_ID, "the re-encoded rung is its own session, not the copy");
1193
- });
1194
-
1195
- test("a file opened at a position starts its sound THERE, not a look-ahead earlier", async (t) => {
1196
- const { manager, base, dirPath } = await managerWithBase();
1197
- t.after(async () => {
1198
- await manager.lifecycle.disposeAll();
1199
- await rm(dirPath, { recursive: true, force: true });
1200
- });
1201
- base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
1202
- // The state at the instant a page is opened at a position: nothing seeked,
1203
- // no segment served, no report from anybody. The read head is then not a
1204
- // request edge — it is where the session was made — and a browser that has
1205
- // just opened holds no buffer at all.
1206
- base.lastRequestedSegment = null;
1207
- manager.viewers.of(base, VIEWER).moveTo(588);
1208
- manager.getCachedAudioTracks = () => [
1209
- { index: 0, language: "rus", title: "", isDefault: true },
1210
- { index: 1, language: "eng", title: "", isDefault: false }
1211
- ];
1212
- const created = [];
1213
- manager.viewerRequests.createOrGetSession = async (params) => {
1214
- created.push(params);
1215
- const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
1216
- return { sessionId: VARIANT_ID, session: rendition };
1217
- };
1218
-
1219
- await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
1220
-
1221
- // Field 2026-08-31: this answered 460 for a page opened at 588 — the whole
1222
- // 120 s look-ahead subtracted from a buffer that did not exist — and the
1223
- // segment the viewer needed took 38.8 s to appear against the picture's 8.4 s.
1224
- assert.equal(
1225
- created[0].startPositionSeconds,
1226
- 584,
1227
- "where the viewer opened, less one segment of margin, and nothing else"
1228
- );
1229
- });
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
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
847
+ return { sessionId: VARIANT_ID, session: rendition };
848
+ };
849
+
850
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
851
+
852
+ assert.equal(created.length, 1, "the track's own session was made");
853
+ assert.equal(
854
+ created[0].startPositionSeconds,
855
+ 96,
856
+ "140 s served, less the 40 s the player holds, less one segment of margin"
857
+ );
858
+ });
859
+
860
+ test("with two viewers the audio track starts at the EARLIEST picture, not the read head", async (t) => {
861
+ const { manager, base, dirPath } = await managerWithBase();
862
+ t.after(async () => {
863
+ await manager.lifecycle.disposeAll();
864
+ await rm(dirPath, { recursive: true, force: true });
865
+ });
866
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
867
+ // A copied picture is one session shared by both of them, and a track begun
868
+ // at the leader has nothing to give the one behind.
869
+ manager.viewers.of(base, "ahead").moveTo(100);
870
+ manager.viewers.of(base, "ahead").playing = false;
871
+ manager.viewers.of(base, "behind").moveTo(40);
872
+ manager.viewers.of(base, "behind").playing = false;
873
+ manager.getCachedAudioTracks = () => [
874
+ { index: 0, language: "rus", title: "", isDefault: true },
875
+ { index: 1, language: "eng", title: "", isDefault: false }
876
+ ];
877
+ const created = [];
878
+ manager.viewerRequests.createOrGetSession = async (params) => {
879
+ created.push(params);
880
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
881
+ return { sessionId: VARIANT_ID, session: rendition };
882
+ };
883
+
884
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
885
+
886
+ assert.equal(
887
+ created[0].startPositionSeconds,
888
+ 36,
889
+ "the viewer at 40 s, less one segment of margin — a run starting at the leader " +
890
+ "has nothing to give the one behind them"
891
+ );
892
+ });
893
+
894
+ test("a soundtrack begins where a viewer says they are, whenever they said it", async (t) => {
895
+ const { manager, base, dirPath } = await managerWithBase();
896
+ t.after(async () => {
897
+ await manager.lifecycle.disposeAll();
898
+ await rm(dirPath, { recursive: true, force: true });
899
+ });
900
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
901
+ // TWO RULES WENT WHEN THE QUANTITY STOPPED MEANING TWO THINGS. A position
902
+ // "past the read head" had to be clamped, because the read head was a
903
+ // request edge and a report could overtake it; and a report older than a few
904
+ // seconds had to be discarded, because it was being subtracted from that
905
+ // edge. Neither survives: this is where the viewer's PICTURE is, they are the
906
+ // only writer of it, and between statements it moves at the rate the film
907
+ // moves. An old statement from a stopped viewer is exactly as true as a new
908
+ // one.
909
+ const viewer = manager.viewers.of(base, "viewer");
910
+ viewer.moveTo(900, Date.now() - 600_000);
911
+ viewer.playing = false;
912
+ manager.getCachedAudioTracks = () => [
913
+ { index: 0, language: "rus", title: "", isDefault: true },
914
+ { index: 1, language: "eng", title: "", isDefault: false }
915
+ ];
916
+ const created = [];
917
+ manager.viewerRequests.createOrGetSession = async (params) => {
918
+ created.push(params);
919
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
920
+ return { sessionId: VARIANT_ID, session: rendition };
921
+ };
922
+
923
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
924
+
925
+ assert.equal(
926
+ created[0].startPositionSeconds,
927
+ 896,
928
+ "ten minutes of silence from a stopped viewer says they are still at 900 s"
929
+ );
930
+ });
931
+
932
+ test("an audio track is prepared at the position the switch will land on", async (t) => {
933
+ const { manager, base, dirPath } = await managerWithBase();
934
+ t.after(async () => {
935
+ await manager.lifecycle.disposeAll();
936
+ await rm(dirPath, { recursive: true, force: true });
937
+ });
938
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
939
+ manager.viewers.of(base, VIEWER).audio = { trackIndex: 1, transcode: true };
940
+ manager.getCachedAudioTracks = () => [
941
+ { index: 0, language: "rus", title: "", isDefault: true },
942
+ { index: 1, language: "eng", title: "", isDefault: false }
943
+ ];
944
+ const rendition = fakeSession({
945
+ id: VARIANT_ID,
946
+ encodeHeight: 0,
947
+ dirPath,
948
+ audioOnly: true,
949
+ audioSourceTrackIndex: 1
950
+ });
951
+ rendition.id = rendition.spec.toName();
952
+ // A soundtrack of THIS picture: the same file, published on its own. Found by
953
+ // what it is — there is no list of ids to put it on.
954
+ rendition.file = base.file;
955
+ startManagedRun(manager, rendition, { process: fakeEncoder() });
956
+ manager.outputs.set(rendition.id, rendition);
957
+
958
+ const prepared = await manager.renditions.prepareAudioTrack(BASE_ID, 1, 240, VIEWER);
959
+
960
+ assert.deepEqual(
961
+ prepared,
962
+ { sessionId: rendition.id, fileName: "segment-00060.mp4" },
963
+ "the caller is told which segment to wait for — 240 s on a four-second grid"
964
+ );
965
+ assert.equal(
966
+ manager.viewers.of(rendition, VIEWER).positionSeconds(),
967
+ 240,
968
+ "and the track is told where this person is, which is what the switch will land on"
969
+ );
970
+ });
971
+
972
+ test("a reading from a soundtrack is priced as one", () => {
973
+ // The fault this pins: an audio rendition reached no learner at all. One
974
+ // guard refused renditions a reading, and the only call that would have
975
+ // priced one sat behind a second guard its caller had already made — so a
976
+ // soundtrack ran for the whole film and was charged at nothing, which is the
977
+ // half of roadmap item 6 that was left owing.
978
+ assert.equal(costKindForSession({ spec: outputSpec({ audioOnly: true }) }), "audio");
979
+ assert.equal(
980
+ costKindForSession({ spec: outputSpec({ audioOnly: true, transcodeVideo: true }) }),
981
+ "audio",
982
+ "a rendition carries no picture, whatever the flag it inherited says"
983
+ );
984
+ assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: true }) }), "decode");
985
+ assert.equal(costKindForSession({ spec: outputSpec({ transcodeVideo: false }) }), "copy");
986
+ });
987
+
988
+ test("a quality step being warmed is not refused by its own cost", async (t) => {
989
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "warm-cost-"));
990
+ // The addon host's own figures, so the arithmetic below is the field's and
991
+ // not an invention. Without a benchmark the check returns every height
992
+ // untouched and a test over it would pass while proving nothing.
993
+ const { manager } = managerWithOwnStore({
994
+ softwarePresetBenchmark: [
995
+ { preset: "fast", pixelsPerSec: 17.0e6 },
996
+ { preset: "ultrafast", pixelsPerSec: 67.5e6 }
997
+ ],
998
+ decodeCostModel: { pixelTerm: 0.007742, bitrateTerm: 0, constantTerm: 0 }
999
+ });
1000
+ t.after(async () => {
1001
+ await manager.lifecycle.disposeAll();
1002
+ await rm(dirPath, { recursive: true, force: true });
1003
+ });
1004
+ // A copied 1080p picture, and a 240p step warmed beside it for a switch —
1005
+ // which is what every quality change does, two encoders on purpose.
1006
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 0, dirPath, transcodeVideo: false });
1007
+ base.variantHeight = 1080;
1008
+ // What this source costs to decode comes from the file's own facts, stated in
1009
+ // the fixture: 1080p24 at 8 Mbit/s, the field file. Without them nothing can
1010
+ // be priced and every height comes back offerable for want of a measurement,
1011
+ // which would make the assertion hold for the wrong reason.
1012
+ assert.ok(base.file.decode, "the fixture must state enough for a decode cost to exist");
1013
+ const warming = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath });
1014
+ warming.variantHeight = 240;
1015
+ // Two sessions of ONE file share its facts, which is the whole point of the
1016
+ // file being an object: a step warmed beside the picture is not a second file.
1017
+ warming.file = base.file;
1018
+ chooseFor(manager, base, 240, warming.outputKey);
1019
+ // A step of the picture: same file, and a height of its own.
1020
+ // Running, and running well: it says of itself that it holds twice realtime,
1021
+ // i.e. half a second of work per second of video.
1022
+ startManagedRun(manager, warming, { process: fakeEncoder() });
1023
+ qualityStateOf(warming).lastAloneSpeed = 2;
1024
+ manager.outputs.set(BASE_ID, base);
1025
+ manager.outputs.set(VARIANT_ID, warming);
1026
+
1027
+ const offered = manager.quality.offeredHeights(base);
1028
+
1029
+ assert.ok(
1030
+ offered.includes(240),
1031
+ "charged its own cost while being judged, the step the viewer just asked for is dropped from the " +
1032
+ "offer by the act of warming it — and its next segment 404s on a stream that is playing"
1033
+ );
1034
+ });
1035
+
1036
+ test("the master survives a live offer that has collapsed to one rung", async (t) => {
1037
+ // The field case of 2026-08-18, in the smallest form that reproduces it: a
1038
+ // host too slow for any re-encoded rung, and a swarm whose interruptions
1039
+ // demand far more than realtime. The live offer then holds only the height an
1040
+ // encoder is already producing — and until this test existed, that made
1041
+ // `buildMasterPlaylist` answer null and the route answer 404 to a session
1042
+ // that had just published the address.
1043
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-collapse-"));
1044
+ const { manager } = managerWithOwnStore({
1045
+ // A megapixel a second: every rung below the source costs more than the
1046
+ // machine has.
1047
+ softwarePresetBenchmark: [{ preset: "veryfast", pixelsPerSec: 1_000_000 }],
1048
+ decodeCostModel: { pixelTerm: 0.01, bitrateTerm: 0, constantTerm: 0 }
1049
+ });
1050
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
1051
+ // A thicker source than the fixture's, stated as the file's own bitrate
1052
+ // rather than as a cost object the file now derives.
1053
+ base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 10_000 });
1054
+ // What this file's own reader measured: a step must run at eight times
1055
+ // realtime to survive this swarm.
1056
+ manager.hostLoad.requiredSpeedFor = () => 8;
1057
+ manager.outputs.set(BASE_ID, base);
1058
+ t.after(async () => {
1059
+ await manager.lifecycle.disposeAll();
1060
+ await rm(dirPath, { recursive: true, force: true });
1061
+ });
1062
+
1063
+ assert.deepEqual(
1064
+ manager.quality.offeredHeights(base),
1065
+ [812],
1066
+ "the live judgement is unchanged: nothing but the running height is worth offering"
1067
+ );
1068
+
1069
+ const master = manager.renditions.buildMasterPlaylist(BASE_ID);
1070
+
1071
+ assert.ok(master, "the master is a published document, not a live figure");
1072
+ const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
1073
+ assert.deepEqual(
1074
+ heights,
1075
+ [1080, 812, 720, 540, 480, 360, 240],
1076
+ "every rung that can be spliced onto this cut grid stays addressable"
1077
+ );
1078
+ });
1079
+
1080
+ test("two heights that clamp onto one picture share a single encoder", async (t) => {
1081
+ const { manager, base, dirPath } = await managerWithBase();
1082
+ const spawnedDirs = [];
1083
+ t.after(async () => {
1084
+ await manager.lifecycle.disposeAll();
1085
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1086
+ await rm(dirPath, { recursive: true, force: true });
1087
+ });
1088
+
1089
+ // A host that can hold exactly one rung. Whatever height is asked for, the
1090
+ // clamp inside createOrGetSession lands the encode on 240p — which is what a
1091
+ // CM4 did on 2026-08-28, turning a 360p and a 540p request into two more
1092
+ // ffmpeg processes making the same 426x240 picture as the 240p one.
1093
+ const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1094
+ const created = [];
1095
+ manager.viewerRequests.createOrGetSession = async (params) => {
1096
+ const id = madeIds[created.length];
1097
+ created.push(params);
1098
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-clamped-"));
1099
+ spawnedDirs.push(variantDir);
1100
+ const variant = fakeSession({ id, encodeHeight: 240, dirPath: variantDir });
1101
+ manager.outputs.set(id, variant);
1102
+ return variant;
1103
+ };
1104
+
1105
+ const asked360 = await askFor(manager, base, 360);
1106
+ const asked540 = await askFor(manager, base, 540);
1107
+
1108
+ assert.equal(asked360.id, VARIANT_ID, "the first request made the encoder");
1109
+ assert.equal(
1110
+ asked540.id,
1111
+ VARIANT_ID,
1112
+ "and the second is served by it, because it produces the very same picture"
1113
+ );
1114
+ assert.equal(
1115
+ manager.outputs.has(SECOND_VARIANT_ID),
1116
+ false,
1117
+ "the duplicate was let go as soon as its size was known"
1118
+ );
1119
+ assert.equal(
1120
+ chosenOutputOf(manager.viewers, VIEWER, 540),
1121
+ manager.outputs.get(VARIANT_ID)?.outputKey,
1122
+ "540p is recorded as answered by the output the machine can hold"
1123
+ );
1124
+
1125
+ const askedAgain = await askFor(manager, base, 540);
1126
+
1127
+ assert.equal(askedAgain.id, VARIANT_ID);
1128
+ assert.equal(created.length, 2, "the third request created nothing at all");
1129
+ });
1130
+
1131
+ test("rungs that really do differ keep their own encoders", async (t) => {
1132
+ const { manager, base, dirPath } = await managerWithBase();
1133
+ const spawnedDirs = [];
1134
+ t.after(async () => {
1135
+ await manager.lifecycle.disposeAll();
1136
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1137
+ await rm(dirPath, { recursive: true, force: true });
1138
+ });
1139
+
1140
+ // A host with room: each request is encoded at the height it named, so
1141
+ // nothing may be merged. The sharing above must not become "one encoder for
1142
+ // every rung".
1143
+ const madeIds = [VARIANT_ID, SECOND_VARIANT_ID];
1144
+ const created = [];
1145
+ manager.viewerRequests.createOrGetSession = async (params) => {
1146
+ const id = madeIds[created.length];
1147
+ created.push(params);
1148
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-distinct-"));
1149
+ spawnedDirs.push(variantDir);
1150
+ const variant = fakeSession({ id, encodeHeight: params.targetHeight, dirPath: variantDir });
1151
+ manager.outputs.set(id, variant);
1152
+ return variant;
1153
+ };
1154
+
1155
+ const asked360 = await askFor(manager, base, 360);
1156
+ const asked540 = await askFor(manager, base, 540);
1157
+
1158
+ assert.equal(asked360.id, VARIANT_ID);
1159
+ assert.equal(asked540.id, SECOND_VARIANT_ID, "two different pictures, two encoders");
1160
+ assert.equal(chosenOutputOf(manager.viewers, VIEWER, 360), asked360.outputKey);
1161
+ assert.equal(chosenOutputOf(manager.viewers, VIEWER, 540), asked540.outputKey);
1162
+ });
1163
+
1164
+ test("a rung is never served from the COPY, whatever height the copy happens to be", async (t) => {
1165
+ const { manager, base, dirPath } = await managerWithBase();
1166
+ const spawnedDirs = [];
1167
+ t.after(async () => {
1168
+ await manager.lifecycle.disposeAll();
1169
+ await Promise.all(spawnedDirs.map((dir) => rm(dir, { recursive: true, force: true })));
1170
+ await rm(dirPath, { recursive: true, force: true });
1171
+ });
1172
+
1173
+ // The base is a COPY at 240p — no encoder behind it, and it is the one rung
1174
+ // this host can always serve. Handing it to a request for a re-encoded 360p
1175
+ // would give away exactly that, and a viewer stranded on a rung the machine
1176
+ // cannot hold would have nowhere left to return to.
1177
+ base.transcodeVideo = false;
1178
+ base.encodeHeight = 240;
1179
+ base.variantHeight = 240;
1180
+ const created = [];
1181
+ manager.viewerRequests.createOrGetSession = async (params) => {
1182
+ created.push(params);
1183
+ const variantDir = await mkdtemp(path.join(os.tmpdir(), "quality-variants-copy-"));
1184
+ spawnedDirs.push(variantDir);
1185
+ const variant = fakeSession({ id: VARIANT_ID, encodeHeight: 240, dirPath: variantDir });
1186
+ manager.outputs.set(VARIANT_ID, variant);
1187
+ return variant;
1188
+ };
1189
+
1190
+ const asked = await askFor(manager, base, 360);
1191
+
1192
+ assert.equal(asked.id, VARIANT_ID, "the re-encoded rung is its own session, not the copy");
1193
+ });
1194
+
1195
+ test("a file opened at a position starts its sound THERE, not a look-ahead earlier", async (t) => {
1196
+ const { manager, base, dirPath } = await managerWithBase();
1197
+ t.after(async () => {
1198
+ await manager.lifecycle.disposeAll();
1199
+ await rm(dirPath, { recursive: true, force: true });
1200
+ });
1201
+ base.spec = outputSpec({ transcodeVideo: true, audioSeparate: true, height: base.output.encodeHeight });
1202
+ // The state at the instant a page is opened at a position: nothing seeked,
1203
+ // no segment served, no report from anybody. The read head is then not a
1204
+ // request edge — it is where the session was made — and a browser that has
1205
+ // just opened holds no buffer at all.
1206
+ base.lastRequestedSegment = null;
1207
+ manager.viewers.of(base, VIEWER).moveTo(588);
1208
+ manager.getCachedAudioTracks = () => [
1209
+ { index: 0, language: "rus", title: "", isDefault: true },
1210
+ { index: 1, language: "eng", title: "", isDefault: false }
1211
+ ];
1212
+ const created = [];
1213
+ manager.viewerRequests.createOrGetSession = async (params) => {
1214
+ created.push(params);
1215
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath, audioOnly: true });
1216
+ return { sessionId: VARIANT_ID, session: rendition };
1217
+ };
1218
+
1219
+ await manager.renditions.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4", VIEWER);
1220
+
1221
+ // Field 2026-08-31: this answered 460 for a page opened at 588 — the whole
1222
+ // 120 s look-ahead subtracted from a buffer that did not exist — and the
1223
+ // segment the viewer needed took 38.8 s to appear against the picture's 8.4 s.
1224
+ assert.equal(
1225
+ created[0].startPositionSeconds,
1226
+ 584,
1227
+ "where the viewer opened, less one segment of margin, and nothing else"
1228
+ );
1229
+ });