@torrent-tv/proxy 2.89.17 → 2.89.18

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