@torrent-tv/proxy 2.75.0 → 2.76.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 (113) hide show
  1. package/CHANGELOG.md +1504 -1461
  2. package/CLAUDE.md +11 -1
  3. package/biome.json +182 -1
  4. package/docs/container-architecture.md +2 -1
  5. package/docs/encode-run-state.md +1 -1
  6. package/knip.json +14 -0
  7. package/package.json +1 -1
  8. package/routes/api/sources/warm/post.js +1 -1
  9. package/routes/api/transcode-sessions/post.js +185 -185
  10. package/routes/api/transcode-sessions/progress/get.js +5 -1
  11. package/routes/transcode/audio-file/get.js +11 -1
  12. package/routes/transcode/audio-warm/get.js +11 -1
  13. package/routes/transcode/session-file/get.js +1 -1
  14. package/routes/transcode/variant-file/get.js +10 -1
  15. package/scripts/render-run-graph.js +2 -2
  16. package/server.js +25 -0
  17. package/services/audio-inventory.js +206 -201
  18. package/services/container/AviContainer.js +1 -1
  19. package/services/container/Container.js +33 -1
  20. package/services/container/MatroskaContainer.js +1 -1
  21. package/services/container/Mp4Container.js +1 -1
  22. package/services/container/SubtitleFileContainer.js +0 -1
  23. package/services/controllers/SubtitleController.js +128 -128
  24. package/services/demand/index.js +7 -10
  25. package/services/download/registry.js +0 -14
  26. package/services/encode/CoverageMap.js +281 -0
  27. package/services/encode/EncodePlan.js +255 -0
  28. package/services/encode/EncodeRun.js +587 -0
  29. package/services/encode/Encoder.js +84 -0
  30. package/services/encode/NvencEncoder.js +45 -0
  31. package/services/encode/QsvEncoder.js +47 -0
  32. package/services/encode/SegmentDemand.js +0 -0
  33. package/services/encode/SegmentStore.js +529 -0
  34. package/services/encode/SoftwareEncoder.js +111 -0
  35. package/services/encode/V4l2m2mEncoder.js +53 -0
  36. package/services/encode/VaapiEncoder.js +53 -0
  37. package/services/encode/args.js +200 -0
  38. package/services/{encode-exit.js → encode/encode-exit.js} +17 -0
  39. package/services/encode/index.js +9 -0
  40. package/services/encode/run-command.js +647 -0
  41. package/services/hls-session-manager.js +11073 -10711
  42. package/services/hwaccel.js +1688 -1992
  43. package/services/orchestrators/EncodeOrchestrator.js +359 -0
  44. package/services/output/LiveOutputs.js +213 -0
  45. package/services/output/Output.js +94 -0
  46. package/services/output/OutputSpec.js +195 -0
  47. package/services/output/Timeline.js +220 -0
  48. package/services/output/index.js +1 -0
  49. package/services/output/ladder.js +26 -0
  50. package/services/playback-planner.js +806 -775
  51. package/services/produced-index.js +222 -300
  52. package/services/source/SourceFile.js +346 -0
  53. package/services/{sidecar-files.js → torrent/files.js} +107 -11
  54. package/services/torrent/naming.js +619 -0
  55. package/services/torrent-worker/client.js +10 -0
  56. package/services/torrent-worker/container-tracks.js +71 -43
  57. package/services/torrent-worker/pool-adapter.js +18 -0
  58. package/services/torrent-worker/protocol.js +7 -0
  59. package/services/torrent-worker/subtitle-cues.js +549 -549
  60. package/services/torrent-worker/worker.js +18 -0
  61. package/services/tracks/TextSubtitleTrack.js +287 -287
  62. package/services/tracks/index.js +15 -14
  63. package/services/viewer/Viewer.js +145 -0
  64. package/services/viewer/Viewers.js +124 -0
  65. package/test/auto-quality-step.test.js +508 -506
  66. package/test/behind-head-repair.test.js +17 -7
  67. package/test/coverage-map.test.js +153 -0
  68. package/test/cut-times-timeline.test.js +6 -5
  69. package/test/cuts-follow-published-grid.test.js +4 -4
  70. package/test/decode-cost.test.js +31 -12
  71. package/test/encode-exit.test.js +1 -1
  72. package/test/encode-orchestrator.test.js +196 -0
  73. package/test/encode-plan.test.js +245 -0
  74. package/test/encode-run-state.test.js +2 -2
  75. package/test/encode-run.test.js +168 -0
  76. package/test/encoder-kinds.test.js +122 -0
  77. package/test/held-request-width.test.js +9 -3
  78. package/test/helpers/encode-run.js +128 -0
  79. package/test/keyframe-index-accuracy.test.js +19 -12
  80. package/test/keyframes-belong-to-the-file.test.js +132 -0
  81. package/test/orchestrator-wired.test.js +164 -0
  82. package/test/output-shape.test.js +68 -0
  83. package/test/output-spec.test.js +157 -0
  84. package/test/produced-copy-choice.test.js +58 -92
  85. package/test/produced-index.test.js +142 -188
  86. package/test/quality-variants.test.js +1079 -1075
  87. package/test/run-graph-drift.test.js +1 -1
  88. package/test/run-intervals.test.js +329 -0
  89. package/test/run-position-follows-published-grid.test.js +4 -4
  90. package/test/seek-landing.test.js +8 -8
  91. package/test/seek-target-not-superseded.test.js +21 -9
  92. package/test/segment-demand.test.js +82 -0
  93. package/test/segment-serve-wiring.test.js +47 -52
  94. package/test/segment-store.test.js +187 -0
  95. package/test/segments-are-shared.test.js +175 -0
  96. package/test/sidecar-naming.test.js +142 -0
  97. package/test/source-file.test.js +133 -0
  98. package/test/stale-request-after-seek.test.js +18 -12
  99. package/test/subtitle-language.test.js +252 -252
  100. package/test/timeline.test.js +95 -0
  101. package/test/{sidecar-files.test.js → torrent-files.test.js} +44 -1
  102. package/test/torrent-naming.test.js +255 -0
  103. package/test/tracks-begin-together.test.js +44 -32
  104. package/test/two-viewers-one-picture.test.js +347 -0
  105. package/test/viewer-outputs.test.js +273 -0
  106. package/test/viewer.test.js +91 -0
  107. package/utils/perf.js +1 -63
  108. package/services/container/index.js +0 -6
  109. package/services/controllers/index.js +0 -2
  110. package/services/download/index.js +0 -8
  111. package/services/orchestrators/index.js +0 -2
  112. /package/services/{encode-run-state.js → encode/encode-run-state.js} +0 -0
  113. /package/services/{language-detect.js → tracks/language-detect.js} +0 -0
@@ -1,506 +1,508 @@
1
- /**
2
- * @file The automatic quality step: what the proxy does when this machine, or
3
- * the viewer's link, cannot carry the picture it is producing.
4
- *
5
- * The rule these tests exist to pin is one sentence long: THE SIZE OF THE
6
- * PICTURE IS NEVER REWRITTEN UNDERNEATH A RUNNING SESSION. The fMP4 init
7
- * segment is fetched once, by `#EXT-X-MAP`, and `avc1` keeps SPS and PPS in it
8
- * rather than in the fragments — so a run that changes the size produces
9
- * fragments the decoder cannot read, silently, with no layer reporting an
10
- * error. Measured 2026-08-21 on two files: one browser reported
11
- * `size=1280x720` for three and a half minutes over macroblock garbage, the
12
- * other errored on the first mismatched fragment and sat at `size=0x0`.
13
- *
14
- * A change of resolution is a change of VARIANT. So the proxy ASKS, the request
15
- * travels in every progress report, and the browser — where the viewer's own
16
- * choice lives — decides whether to follow it.
17
- */
18
-
19
- import test from "node:test";
20
- import assert from "node:assert/strict";
21
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
22
- import os from "node:os";
23
- import path from "node:path";
24
- import { HlsSessionManager } from "../services/hls-session-manager.js";
25
- import { fmp4Format } from "../services/segment-formats/fmp4.js";
26
- import { softwareDescriptor, maxrateKbpsFor, nominalKbpsForHeight } from "../services/hwaccel.js";
27
- import { readVideoSampleSize } from "../services/segment-formats/mp4-boxes.js";
28
-
29
- const BASE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
30
- const SEGMENT_SECONDS = 4;
31
-
32
- /** A child process that is alive as far as the budget is concerned. */
33
- function fakeEncoder() {
34
- return {
35
- pid: 4321,
36
- exitCode: null,
37
- signalCode: null,
38
- kill() {},
39
- once(event, handler) {
40
- if (event === "exit") {
41
- handler();
42
- }
43
- }
44
- };
45
- }
46
-
47
- /**
48
- * A session shaped like a live one, encoding 720p of a 1080p source.
49
- *
50
- * @param {{ dirPath: string, transcodeVideo?: boolean, cutGrid?: string }} params
51
- * @returns {object}
52
- */
53
- function fakeSession({ dirPath, transcodeVideo = true, cutGrid = "keyframe" }) {
54
- return {
55
- id: BASE_ID,
56
- // A copy can only be cut where the source already has a keyframe, so this
57
- // is what decides whether it publishes variants at all.
58
- cutGrid,
59
- dirPath,
60
- state: "ready",
61
- fileName: "video.mkv",
62
- startedAt: Date.now(),
63
- lastAccessedAt: Date.now(),
64
- ffmpeg: fakeEncoder(),
65
- runState: "running",
66
- runSerial: 1,
67
- lastError: "",
68
- consumers: new Set(),
69
- segmentFormat: fmp4Format,
70
- transcodeVideo,
71
- transcodeAudio: true,
72
- audioOnly: false,
73
- audioTrackIndex: 0,
74
- sourceKey: "source-1",
75
- fileIndex: 0,
76
- sourceWidth: 1920,
77
- sourceHeight: 1080,
78
- encodeWidth: transcodeVideo ? 1280 : 0,
79
- encodeHeight: transcodeVideo ? 720 : 0,
80
- outputFps: 24,
81
- encodeRunGeneration: 0,
82
- encodeStartIndex: 0,
83
- budgetSlowSince: 0,
84
- budgetUpSince: 0,
85
- budgetLastActionAt: 0,
86
- qualityAsk: null,
87
- initSizeSaid: "",
88
- recentSpeed: null,
89
- rateCapKbps: null,
90
- netReports: new Map(),
91
- linkSlowSince: 0,
92
- lastAloneSpeed: null,
93
- durationSeconds: 400,
94
- totalDurationSeconds: 400,
95
- usesExplicitCuts: false,
96
- useSyntheticPlaylist: true,
97
- playlistText: "#EXTM3U\n",
98
- segmentBoundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
99
- segmentCount: 100,
100
- progress: { state: "running", processedSeconds: 40, startPositionSeconds: 0, speed: "1.0x" }
101
- };
102
- }
103
-
104
- /**
105
- * @param {{ transcodeVideo?: boolean, cutGrid?: string }} [options]
106
- * @returns {Promise<{ manager: HlsSessionManager, session: object, dirPath: string, restarts: number[] }>}
107
- */
108
- async function managerWithSession({ transcodeVideo = true, cutGrid = "keyframe" } = {}) {
109
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "auto-quality-"));
110
- const manager = new HlsSessionManager({
111
- enabled: true,
112
- ffmpegBin: "ffmpeg",
113
- localBindHost: "127.0.0.1",
114
- localPort: 9090
115
- });
116
- // A software host: the budget's own precondition.
117
- manager.videoEncoder = { kind: "software", name: "libx264", inputArgs: [] };
118
- // A fully-downloaded file, so nothing here is ever read as download-bound —
119
- // the distinction is tested elsewhere and would only obscure these.
120
- manager.getSourceStats = async () => ({
121
- downloadSpeed: 10e6,
122
- fileProgress: 1,
123
- fileLength: 4e9
124
- });
125
- const session = fakeSession({ dirPath, transcodeVideo, cutGrid });
126
- manager.sessionsById.set(BASE_ID, session);
127
- return { manager, session, dirPath };
128
- }
129
-
130
- /**
131
- * Produced segments of a known size, so the observed stream bitrate the link
132
- * check compares against is a real reading of real files.
133
- *
134
- * @param {object} session
135
- * @param {number} bytesEach
136
- * @returns {Promise<void>}
137
- */
138
- async function produceSegments(session, bytesEach) {
139
- // Where a run really writes: the manager reads produced files out of the
140
- // `run-N` directories, not out of the session directory itself.
141
- const runDir = path.join(session.dirPath, `run-${session.runSerial}`);
142
- await mkdir(runDir, { recursive: true });
143
- session.runDirPath = runDir;
144
- for (let index = 0; index < 4; index += 1) {
145
- await writeFile(
146
- path.join(runDir, session.segmentFormat.segmentFileName(index)),
147
- Buffer.alloc(bytesEach)
148
- );
149
- }
150
- }
151
-
152
- test("a picture that cannot be kept up with is asked for as another VARIANT, and its size is left alone", async (t) => {
153
- const { manager, session, dirPath } = await managerWithSession();
154
- t.after(async () => {
155
- await manager.disposeAll();
156
- await rm(dirPath, { recursive: true, force: true });
157
- });
158
-
159
- const sizeBefore = `${session.encodeWidth}x${session.encodeHeight}`;
160
- // Sustained sub-realtime, read as a slope: the run has been slow since well
161
- // before the window, and the reading is from this very run.
162
- session.budgetSlowSince = Date.now() - 60_000;
163
- session.recentSpeed = { speed: 0.7, at: Date.now(), runSerial: session.runSerial };
164
-
165
- await manager.runQualityBudgetOnce();
166
-
167
- assert.equal(
168
- `${session.encodeWidth}x${session.encodeHeight}`,
169
- sizeBefore,
170
- "the size the init segment describes must survive the step — that is the whole fault"
171
- );
172
- assert.ok(session.qualityAsk, "the step is a request to the player to move variant");
173
- assert.ok(
174
- session.qualityAsk.height < 720,
175
- `a step DOWN, and 720p was on screen (asked for ${session.qualityAsk?.height}p)`
176
- );
177
- });
178
-
179
- test("the request reaches the browser in the progress report, and stops once the viewer is there", async (t) => {
180
- const { manager, session, dirPath } = await managerWithSession();
181
- t.after(async () => {
182
- await manager.disposeAll();
183
- await rm(dirPath, { recursive: true, force: true });
184
- });
185
-
186
- session.qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
187
- const asked = await manager.getSessionProgress(BASE_ID);
188
- assert.equal(asked.requestedHeight, 480, "the request travels with every progress report");
189
-
190
- // The player moved: the variant it is now watching IS the height asked for.
191
- session.variantHeight = 480;
192
- const answered = await manager.getSessionProgress(BASE_ID);
193
- assert.equal(answered.requestedHeight, 0, "a request the viewer has answered is not repeated");
194
- assert.equal(session.qualityAsk, null, "and it is let go of, not merely hidden");
195
- });
196
-
197
- test("a request the player never follows runs out instead of being repeated for the whole film", async (t) => {
198
- const { manager, session, dirPath } = await managerWithSession();
199
- t.after(async () => {
200
- await manager.disposeAll();
201
- await rm(dirPath, { recursive: true, force: true });
202
- });
203
-
204
- // A viewer on a manual pick ignores every request by design, and so does a
205
- // stream with no variants. Neither is an error; both look the same from here.
206
- session.qualityAsk = { height: 480, at: Date.now() - 120_000, reason: "measured" };
207
-
208
- const progress = await manager.getSessionProgress(BASE_ID);
209
-
210
- assert.equal(progress.requestedHeight, 0);
211
- assert.equal(session.qualityAsk, null, "said once and let go");
212
- });
213
-
214
- test("a COPIED picture is never asked to slow its encoder, because it has none", async (t) => {
215
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
216
- t.after(async () => {
217
- await manager.disposeAll();
218
- await rm(dirPath, { recursive: true, force: true });
219
- });
220
-
221
- // Whatever this reading says, a copy has no encoder to make cheaper: moving
222
- // the viewer to a RE-ENCODED rung costs the machine more, not less.
223
- session.budgetSlowSince = Date.now() - 60_000;
224
- session.recentSpeed = { speed: 0.4, at: Date.now(), runSerial: session.runSerial };
225
-
226
- await manager.runQualityBudgetOnce();
227
-
228
- assert.equal(session.qualityAsk, null, "the copy path's lever is the viewer's link, not the CPU");
229
- });
230
-
231
- test("a measured link becomes the encoder's own bitrate ceiling, and nothing else moves", () => {
232
- // The one lever that reduces what is sent without touching the picture:
233
- // -maxrate/-bufsize and CRF do not appear in the SPS, so the init segment
234
- // already in the player's hands goes on describing every fragment.
235
- const uncapped = softwareDescriptor().buildVideoArgs({
236
- targetWidth: 1280,
237
- targetHeight: 720,
238
- segmentDurationSec: 4,
239
- fps: 24
240
- });
241
- const capped = softwareDescriptor().buildVideoArgs({
242
- targetWidth: 1280,
243
- targetHeight: 720,
244
- segmentDurationSec: 4,
245
- fps: 24,
246
- nominalKbps: 1200
247
- });
248
-
249
- assert.equal(
250
- uncapped[uncapped.indexOf("-maxrate") + 1],
251
- `${maxrateKbpsFor(nominalKbpsForHeight(720))}k`,
252
- "with nothing measured the rung's own nominal rate stands"
253
- );
254
- assert.equal(capped[capped.indexOf("-maxrate") + 1], `${maxrateKbpsFor(1200)}k`);
255
- // Everything that decides the SIZE must be identical in the two.
256
- assert.deepEqual(
257
- uncapped.slice(0, uncapped.indexOf("-maxrate")),
258
- capped.slice(0, capped.indexOf("-maxrate")),
259
- "the scale filter, the codec and the preset are untouched by a rate cap"
260
- );
261
- });
262
-
263
- test("the size an init segment describes is read from the init, not assumed", () => {
264
- // A minimal moov/trak/mdia/minf/stbl/stsd with one avc1 entry. Built here
265
- // rather than taken from a fixture so the offsets under test are the ones
266
- // ISO/IEC 14496-12 states, and a fixture cannot quietly encode a mistake.
267
- const avc1 = Buffer.alloc(8 + 8 + 16 + 4);
268
- avc1.writeUInt32BE(avc1.length, 0);
269
- avc1.write("avc1", 4, "latin1");
270
- avc1.writeUInt16BE(960, 32);
271
- avc1.writeUInt16BE(540, 34);
272
-
273
- const stsd = Buffer.concat([Buffer.alloc(8 + 8), avc1]);
274
- stsd.writeUInt32BE(stsd.length, 0);
275
- stsd.write("stsd", 4, "latin1");
276
- stsd.writeUInt32BE(1, 12); // entry_count
277
-
278
- const wrap = (type, payload) => {
279
- const box = Buffer.alloc(8 + payload.length);
280
- box.writeUInt32BE(box.length, 0);
281
- box.write(type, 4, "latin1");
282
- payload.copy(box, 8);
283
- return box;
284
- };
285
- const init = wrap("moov", wrap("trak", wrap("mdia", wrap("minf", wrap("stbl", stsd)))));
286
-
287
- assert.deepEqual(readVideoSampleSize(init), { width: 960, height: 540 });
288
- assert.equal(readVideoSampleSize(Buffer.alloc(0)), null);
289
- });
290
-
291
- test("a COPIED picture too thick for the viewer's link is asked for as a smaller VARIANT", async (t) => {
292
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
293
- t.after(async () => {
294
- await manager.disposeAll();
295
- await rm(dirPath, { recursive: true, force: true });
296
- });
297
-
298
- // Four seconds of segment at 2 MB is ~4 Mbit/s of stream. The viewer reports
299
- // a link that cannot carry it and a buffer that is running dry.
300
- await produceSegments(session, 2_000_000);
301
- session.netReports.set("viewer", { linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: null, at: Date.now() });
302
- session.linkSlowSince = Date.now() - 60_000;
303
-
304
- await manager.runQualityBudgetOnce();
305
-
306
- assert.ok(
307
- session.qualityAsk,
308
- "a copy has no encoder to bound, so the only way to send fewer bits is another rendering of the film"
309
- );
310
- assert.ok(session.qualityAsk.height < 1080, `a step down (asked for ${session.qualityAsk?.height}p)`);
311
- });
312
-
313
- test("with two viewers the budget acts on the WORST link, not on whoever reported last", async (t) => {
314
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
315
- t.after(async () => {
316
- await manager.disposeAll();
317
- await rm(dirPath, { recursive: true, force: true });
318
- });
319
-
320
- await produceSegments(session, 2_000_000);
321
- // One viewer is comfortable and reported LAST, which under a single field was
322
- // the whole of what the budget saw. The other cannot carry the stream and is
323
- // running dry.
324
- session.netReports.set("thin", {
325
- linkMbps: 1.0,
326
- bufferedAheadSec: 1.5,
327
- positionSeconds: 40,
328
- at: Date.now() - 1_000
329
- });
330
- session.netReports.set("fat", {
331
- linkMbps: 80,
332
- bufferedAheadSec: 60,
333
- positionSeconds: 40,
334
- at: Date.now()
335
- });
336
- session.linkSlowSince = Date.now() - 60_000;
337
-
338
- await manager.runQualityBudgetOnce();
339
-
340
- assert.ok(
341
- session.qualityAsk,
342
- "the viewer who cannot keep up decides, whichever of them reported most recently"
343
- );
344
- });
345
-
346
- test("a report from a viewer who has left stops counting", async (t) => {
347
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
348
- t.after(async () => {
349
- await manager.disposeAll();
350
- await rm(dirPath, { recursive: true, force: true });
351
- });
352
-
353
- await produceSegments(session, 2_000_000);
354
- // Nothing releases a consumer when a data channel closes (roadmap item 55),
355
- // so a departed viewer's last reading would otherwise go on deciding for the
356
- // one still here. It is dropped on the next report rather than kept.
357
- session.netReports.set("gone", {
358
- linkMbps: 1.0,
359
- bufferedAheadSec: 1.5,
360
- positionSeconds: 40,
361
- at: Date.now() - 120_000
362
- });
363
- manager.recordNetReport(session.id, {
364
- linkMbps: 80,
365
- bufferedAheadSec: 60,
366
- consumerId: "here",
367
- positionSeconds: 40
368
- });
369
- session.linkSlowSince = Date.now() - 60_000;
370
-
371
- await manager.runQualityBudgetOnce();
372
-
373
- assert.equal(session.netReports.size, 1, "the stale entry was removed, not merely ignored");
374
- assert.equal(session.qualityAsk, null, "the viewer who is here can carry the picture");
375
- });
376
-
377
- test("the way BACK UP exists, and a bitrate cap is lifted before the picture is enlarged", async (t) => {
378
- const { manager, session, dirPath } = await managerWithSession();
379
- t.after(async () => {
380
- await manager.disposeAll();
381
- await rm(dirPath, { recursive: true, force: true });
382
- });
383
-
384
- // The viewer is on 480p, the machine has been ahead of realtime for longer
385
- // than the up window, and nothing is capping the bitrate.
386
- session.variantHeight = 480;
387
- session.encodeWidth = 854;
388
- session.encodeHeight = 480;
389
- session.recentSpeed = { speed: 2.4, at: Date.now(), runSerial: session.runSerial };
390
- session.budgetUpSince = Date.now() - 120_000;
391
-
392
- await manager.runQualityBudgetOnce();
393
-
394
- assert.ok(session.qualityAsk, "for most of this project's life there was no step up at all");
395
- assert.equal(
396
- session.qualityAsk.height,
397
- 540,
398
- "one rung at a time: the lowest height above the one on screen, never above the source"
399
- );
400
- });
401
-
402
- test("a capped picture gets its own bitrate back before it is asked to grow", async (t) => {
403
- const { manager, session, dirPath } = await managerWithSession();
404
- t.after(async () => {
405
- await manager.disposeAll();
406
- await rm(dirPath, { recursive: true, force: true });
407
- });
408
-
409
- session.variantHeight = 480;
410
- session.encodeWidth = 854;
411
- session.encodeHeight = 480;
412
- session.rateCapKbps = 700;
413
- session.recentSpeed = { speed: 2.4, at: Date.now(), runSerial: session.runSerial };
414
- session.budgetUpSince = Date.now() - 120_000;
415
- // A restart is what lifting the cap costs, and spawning ffmpeg is not this
416
- // test's business — the session is left with no encoder to replace, which is
417
- // the same path a run that has already ended takes.
418
- session.ffmpeg = fakeEncoder();
419
-
420
- await manager.runQualityBudgetOnce().catch(() => undefined);
421
-
422
- assert.equal(session.rateCapKbps, null, "the cap goes first: it is cheaper than enlarging the picture");
423
- assert.equal(
424
- session.qualityAsk,
425
- null,
426
- "and the height is left for a second unbroken window, so the two do not move at once"
427
- );
428
- });
429
-
430
- test("a stream that publishes no variants is left alone, and said so once", async (t) => {
431
- const { manager, session, dirPath } = await managerWithSession({
432
- transcodeVideo: false,
433
- // A copy whose keyframe index could not be read falls back to an even grid
434
- // ffmpeg does not cut on. Nothing can be aligned to that, so there is no
435
- // master and no variant to move to.
436
- cutGrid: "even"
437
- });
438
- t.after(async () => {
439
- await manager.disposeAll();
440
- await rm(dirPath, { recursive: true, force: true });
441
- });
442
-
443
- await produceSegments(session, 2_000_000);
444
- session.netReports.set("viewer", { linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: null, at: Date.now() });
445
- session.linkSlowSince = Date.now() - 60_000;
446
-
447
- await manager.runQualityBudgetOnce();
448
-
449
- assert.equal(session.qualityAsk, null, "asking a player with no variants to change variant is nothing");
450
- assert.equal(session.saidNoVariants, true, "and the reason is stated once, not once per window");
451
- });
452
-
453
- test("a height this machine has been MEASURED failing at is not what the way back up offers", async (t) => {
454
- const { manager, session, dirPath } = await managerWithSession();
455
- t.after(async () => {
456
- await manager.disposeAll();
457
- await rm(dirPath, { recursive: true, force: true });
458
- });
459
-
460
- // The base ran 720p at half realtime and the viewer was stepped down to 480p.
461
- // The base's own height used to be exempt from every refusal — it was the
462
- // rung on screen, back when a step changed the encode inside it so the way
463
- // back up would have asked for 720p again, failed again, and stepped down
464
- // again, about every hundred seconds for the length of the film.
465
- manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 1e6 }];
466
- session.lastAloneSpeed = 0.5;
467
- session.variantHeight = 720;
468
-
469
- const offered = manager.offeredHeights(session);
470
-
471
- assert.ok(!offered.includes(720) || manager.variantHeightOf(session) === 720);
472
- // Now on the 480p variant: 720p has a reading of its own and must be gone.
473
- session.variantHeight = 480;
474
- session.encodeHeight = 480;
475
- session.encodeWidth = 854;
476
- assert.ok(
477
- !manager.offeredHeights(session).includes(720),
478
- "a rung measured below realtime is withdrawn once the viewer has left it"
479
- );
480
- });
481
-
482
- test("a cap is not lifted because there is no higher rung to compare against", async (t) => {
483
- const { manager, session, dirPath } = await managerWithSession();
484
- t.after(async () => {
485
- await manager.disposeAll();
486
- await rm(dirPath, { recursive: true, force: true });
487
- });
488
-
489
- // At the top offered height, so there is no NEXT rung — and the question of
490
- // whether to lift the cap is about THIS one. Deciding it on "nothing to step
491
- // to, so yes" took the cap off a link measured at a fifth of what the picture
492
- // needs, after which #checkLinkBudget put it straight back: two ffmpeg
493
- // restarts a minute and a half, on exactly the thin cellular viewer the cap
494
- // exists for.
495
- session.variantHeight = 1080;
496
- session.encodeWidth = 1920;
497
- session.encodeHeight = 1080;
498
- session.rateCapKbps = 700;
499
- session.recentSpeed = { speed: 2.4, at: Date.now(), runSerial: session.runSerial };
500
- session.budgetUpSince = Date.now() - 120_000;
501
- session.netReports.set("viewer", { linkMbps: 1.0, bufferedAheadSec: 30, positionSeconds: null, at: Date.now() });
502
-
503
- await manager.runQualityBudgetOnce();
504
-
505
- assert.equal(session.rateCapKbps, 700, "the link still cannot carry this picture uncapped");
506
- });
1
+ /**
2
+ * @file The automatic quality step: what the proxy does when this machine, or
3
+ * the viewer's link, cannot carry the picture it is producing.
4
+ *
5
+ * The rule these tests exist to pin is one sentence long: THE SIZE OF THE
6
+ * PICTURE IS NEVER REWRITTEN UNDERNEATH A RUNNING SESSION. The fMP4 init
7
+ * segment is fetched once, by `#EXT-X-MAP`, and `avc1` keeps SPS and PPS in it
8
+ * rather than in the fragments — so a run that changes the size produces
9
+ * fragments the decoder cannot read, silently, with no layer reporting an
10
+ * error. Measured 2026-08-21 on two files: one browser reported
11
+ * `size=1280x720` for three and a half minutes over macroblock garbage, the
12
+ * other errored on the first mismatched fragment and sat at `size=0x0`.
13
+ *
14
+ * A change of resolution is a change of VARIANT. So the proxy ASKS, the request
15
+ * travels in every progress report, and the browser — where the viewer's own
16
+ * choice lives — decides whether to follow it.
17
+ */
18
+
19
+ import test from "node:test";
20
+ import { fakeProcess as fakeEncoder, startRunOn } from "./helpers/encode-run.js";
21
+ import assert from "node:assert/strict";
22
+ import { SourceFile } from "../services/source/SourceFile.js";
23
+ import { Timeline } from "../services/output/Timeline.js";
24
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
25
+ import os from "node:os";
26
+ import path from "node:path";
27
+ import { HlsSessionManager } from "../services/hls-session-manager.js";
28
+ import { Output } from "../services/output/Output.js";
29
+ import { viewerOf } from "../services/viewer/Viewer.js";
30
+ import { fmp4Format } from "../services/segment-formats/fmp4.js";
31
+ import { softwareDescriptor, maxrateKbpsFor, nominalKbpsForHeight } from "../services/hwaccel.js";
32
+ import { readVideoSampleSize } from "../services/segment-formats/mp4-boxes.js";
33
+
34
+ const BASE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
35
+ const SEGMENT_SECONDS = 4;
36
+
37
+
38
+ /**
39
+ * A session shaped like a live one, encoding 720p of a 1080p source.
40
+ *
41
+ * @param {{ dirPath: string, transcodeVideo?: boolean, cutGrid?: string }} params
42
+ * `cutGrid` goes into the file's cut table; left out, it is what production
43
+ * builds for this branch.
44
+ * @returns {object}
45
+ */
46
+ function fakeSession({ dirPath, transcodeVideo = true, cutGrid = transcodeVideo ? "uniform" : "keyframe" }) {
47
+ return {
48
+ id: BASE_ID,
49
+ dirPath,
50
+ // Where this file is cut, held by the file. A fixture that stated it
51
+ // on the session was describing what production no longer does.
52
+ //
53
+ // The grid travels in here and nowhere else: a copy can only be cut where
54
+ // the source already has a keyframe, so this is what decides whether the
55
+ // stream publishes variants at all, and `#publishesVariants` reads it off
56
+ // the table. The default is what production builds a keyframe grid only
57
+ // where one was read, which is the copy.
58
+ timeline: new Timeline({
59
+ boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
60
+ cutGrid
61
+ }),
62
+ state: "ready",
63
+ file: new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080, durationSeconds: 400 }),
64
+ // An ordinary session reads its own file, and its sound is inside it. The
65
+ // three differ only for a soundtrack shipped as a file of its own.
66
+ get inputFile() { return this.file; },
67
+ get audioFile() { return this.file; },
68
+ startedAt: Date.now(),
69
+ lastAccessedAt: Date.now(),
70
+ runs: new Set(),
71
+ runState: "running",
72
+ runSerial: 1,
73
+ lastError: "",
74
+ consumers: new Set(),
75
+ segmentFormat: fmp4Format,
76
+ transcodeVideo,
77
+ transcodeAudio: true,
78
+ audioOnly: false,
79
+ audioTrackIndex: 0,
80
+ // The shape this output is encoded AS, decided once for the output.
81
+ output: new Output({
82
+ encodeWidth: transcodeVideo ? 1280 : 0,
83
+ encodeHeight: transcodeVideo ? 720 : 0,
84
+ outputFps: 24,
85
+ softwarePreset: null,
86
+ applyTonemap: false
87
+ }),
88
+ encodeRunGeneration: 0,
89
+ budgetSlowSince: 0,
90
+ budgetUpSince: 0,
91
+ budgetLastActionAt: 0,
92
+ qualityAsk: null,
93
+ initSizeSaid: "",
94
+ recentSpeed: null,
95
+ rateCapKbps: null,
96
+ viewers: new Map(),
97
+ linkSlowSince: 0,
98
+ lastAloneSpeed: null,
99
+ usesExplicitCuts: false,
100
+ useSyntheticPlaylist: true,
101
+ playlistText: "#EXTM3U\n",
102
+ segmentCount: 100,
103
+ progress: { state: "running", processedSeconds: 40, startPositionSeconds: 0, speed: "1.0x" }
104
+ };
105
+ }
106
+
107
+ /**
108
+ * @param {{ transcodeVideo?: boolean, cutGrid?: string }} [options]
109
+ * @returns {Promise<{ manager: HlsSessionManager, session: object, dirPath: string, restarts: number[] }>}
110
+ */
111
+ async function managerWithSession({ transcodeVideo = true, cutGrid } = {}) {
112
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "auto-quality-"));
113
+ const manager = new HlsSessionManager({
114
+ enabled: true,
115
+ ffmpegBin: "ffmpeg",
116
+ localBindHost: "127.0.0.1",
117
+ localPort: 9090
118
+ });
119
+ // A software host: the budget's own precondition.
120
+ manager.videoEncoder = { kind: "software", name: "libx264", inputArgs: [] };
121
+ // A fully-downloaded file, so nothing here is ever read as download-bound —
122
+ // the distinction is tested elsewhere and would only obscure these.
123
+ manager.getSourceStats = async () => ({
124
+ downloadSpeed: 10e6,
125
+ fileProgress: 1,
126
+ fileLength: 4e9
127
+ });
128
+ const session = fakeSession({ dirPath, transcodeVideo, cutGrid });
129
+ manager.sessionsById.set(BASE_ID, session);
130
+ startRunOn(session, { process: fakeEncoder() });
131
+ return { manager, session, dirPath };
132
+ }
133
+
134
+ /**
135
+ * Produced segments of a known size, so the observed stream bitrate the link
136
+ * check compares against is a real reading of real files.
137
+ *
138
+ * @param {object} session
139
+ * @param {number} bytesEach
140
+ * @returns {Promise<void>}
141
+ */
142
+ async function produceSegments(session, bytesEach) {
143
+ // Where the run in force writes.
144
+ const runDir = session.dirPath;
145
+ await mkdir(runDir, { recursive: true });
146
+ for (let index = 0; index < 4; index += 1) {
147
+ await writeFile(
148
+ path.join(runDir, session.segmentFormat.segmentFileName(index)),
149
+ Buffer.alloc(bytesEach)
150
+ );
151
+ }
152
+ }
153
+
154
+ test("a picture that cannot be kept up with is asked for as another VARIANT, and its size is left alone", async (t) => {
155
+ const { manager, session, dirPath } = await managerWithSession();
156
+ t.after(async () => {
157
+ await manager.disposeAll();
158
+ await rm(dirPath, { recursive: true, force: true });
159
+ });
160
+
161
+ const sizeBefore = `${session.encodeWidth}x${session.encodeHeight}`;
162
+ // Sustained sub-realtime, read as a slope: the run has been slow since well
163
+ // before the window, and the reading is from this very run.
164
+ session.budgetSlowSince = Date.now() - 60_000;
165
+ session.recentSpeed = { speed: 0.7, at: Date.now(), run: [...session.runs][0] };
166
+
167
+ await manager.runQualityBudgetOnce();
168
+
169
+ assert.equal(
170
+ `${session.encodeWidth}x${session.encodeHeight}`,
171
+ sizeBefore,
172
+ "the size the init segment describes must survive the step that is the whole fault"
173
+ );
174
+ assert.ok(session.qualityAsk, "the step is a request to the player to move variant");
175
+ assert.ok(
176
+ session.qualityAsk.height < 720,
177
+ `a step DOWN, and 720p was on screen (asked for ${session.qualityAsk?.height}p)`
178
+ );
179
+ });
180
+
181
+ test("the request reaches the browser in the progress report, and stops once the viewer is there", async (t) => {
182
+ const { manager, session, dirPath } = await managerWithSession();
183
+ t.after(async () => {
184
+ await manager.disposeAll();
185
+ await rm(dirPath, { recursive: true, force: true });
186
+ });
187
+
188
+ session.qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
189
+ const asked = await manager.getSessionProgress(BASE_ID);
190
+ assert.equal(asked.requestedHeight, 480, "the request travels with every progress report");
191
+
192
+ // The player moved: the variant it is now watching IS the height asked for.
193
+ session.variantHeight = 480;
194
+ const answered = await manager.getSessionProgress(BASE_ID);
195
+ assert.equal(answered.requestedHeight, 0, "a request the viewer has answered is not repeated");
196
+ assert.equal(session.qualityAsk, null, "and it is let go of, not merely hidden");
197
+ });
198
+
199
+ test("a request the player never follows runs out instead of being repeated for the whole film", async (t) => {
200
+ const { manager, session, dirPath } = await managerWithSession();
201
+ t.after(async () => {
202
+ await manager.disposeAll();
203
+ await rm(dirPath, { recursive: true, force: true });
204
+ });
205
+
206
+ // A viewer on a manual pick ignores every request by design, and so does a
207
+ // stream with no variants. Neither is an error; both look the same from here.
208
+ session.qualityAsk = { height: 480, at: Date.now() - 120_000, reason: "measured" };
209
+
210
+ const progress = await manager.getSessionProgress(BASE_ID);
211
+
212
+ assert.equal(progress.requestedHeight, 0);
213
+ assert.equal(session.qualityAsk, null, "said once and let go");
214
+ });
215
+
216
+ test("a COPIED picture is never asked to slow its encoder, because it has none", async (t) => {
217
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
218
+ t.after(async () => {
219
+ await manager.disposeAll();
220
+ await rm(dirPath, { recursive: true, force: true });
221
+ });
222
+
223
+ // Whatever this reading says, a copy has no encoder to make cheaper: moving
224
+ // the viewer to a RE-ENCODED rung costs the machine more, not less.
225
+ session.budgetSlowSince = Date.now() - 60_000;
226
+ session.recentSpeed = { speed: 0.4, at: Date.now(), run: [...session.runs][0] };
227
+
228
+ await manager.runQualityBudgetOnce();
229
+
230
+ assert.equal(session.qualityAsk, null, "the copy path's lever is the viewer's link, not the CPU");
231
+ });
232
+
233
+ test("a measured link becomes the encoder's own bitrate ceiling, and nothing else moves", () => {
234
+ // The one lever that reduces what is sent without touching the picture:
235
+ // -maxrate/-bufsize and CRF do not appear in the SPS, so the init segment
236
+ // already in the player's hands goes on describing every fragment.
237
+ const uncapped = softwareDescriptor().buildVideoArgs({
238
+ targetWidth: 1280,
239
+ targetHeight: 720,
240
+ segmentDurationSec: 4,
241
+ fps: 24
242
+ });
243
+ const capped = softwareDescriptor().buildVideoArgs({
244
+ targetWidth: 1280,
245
+ targetHeight: 720,
246
+ segmentDurationSec: 4,
247
+ fps: 24,
248
+ nominalKbps: 1200
249
+ });
250
+
251
+ assert.equal(
252
+ uncapped[uncapped.indexOf("-maxrate") + 1],
253
+ `${maxrateKbpsFor(nominalKbpsForHeight(720))}k`,
254
+ "with nothing measured the rung's own nominal rate stands"
255
+ );
256
+ assert.equal(capped[capped.indexOf("-maxrate") + 1], `${maxrateKbpsFor(1200)}k`);
257
+ // Everything that decides the SIZE must be identical in the two.
258
+ assert.deepEqual(
259
+ uncapped.slice(0, uncapped.indexOf("-maxrate")),
260
+ capped.slice(0, capped.indexOf("-maxrate")),
261
+ "the scale filter, the codec and the preset are untouched by a rate cap"
262
+ );
263
+ });
264
+
265
+ test("the size an init segment describes is read from the init, not assumed", () => {
266
+ // A minimal moov/trak/mdia/minf/stbl/stsd with one avc1 entry. Built here
267
+ // rather than taken from a fixture so the offsets under test are the ones
268
+ // ISO/IEC 14496-12 states, and a fixture cannot quietly encode a mistake.
269
+ const avc1 = Buffer.alloc(8 + 8 + 16 + 4);
270
+ avc1.writeUInt32BE(avc1.length, 0);
271
+ avc1.write("avc1", 4, "latin1");
272
+ avc1.writeUInt16BE(960, 32);
273
+ avc1.writeUInt16BE(540, 34);
274
+
275
+ const stsd = Buffer.concat([Buffer.alloc(8 + 8), avc1]);
276
+ stsd.writeUInt32BE(stsd.length, 0);
277
+ stsd.write("stsd", 4, "latin1");
278
+ stsd.writeUInt32BE(1, 12); // entry_count
279
+
280
+ const wrap = (type, payload) => {
281
+ const box = Buffer.alloc(8 + payload.length);
282
+ box.writeUInt32BE(box.length, 0);
283
+ box.write(type, 4, "latin1");
284
+ payload.copy(box, 8);
285
+ return box;
286
+ };
287
+ const init = wrap("moov", wrap("trak", wrap("mdia", wrap("minf", wrap("stbl", stsd)))));
288
+
289
+ assert.deepEqual(readVideoSampleSize(init), { width: 960, height: 540 });
290
+ assert.equal(readVideoSampleSize(Buffer.alloc(0)), null);
291
+ });
292
+
293
+ test("a COPIED picture too thick for the viewer's link is asked for as a smaller VARIANT", async (t) => {
294
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
295
+ t.after(async () => {
296
+ await manager.disposeAll();
297
+ await rm(dirPath, { recursive: true, force: true });
298
+ });
299
+
300
+ // Four seconds of segment at 2 MB is ~4 Mbit/s of stream. The viewer reports
301
+ // a link that cannot carry it and a buffer that is running dry.
302
+ await produceSegments(session, 2_000_000);
303
+ viewerOf(session, "viewer").netReport = { linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: null, at: Date.now() };
304
+ session.linkSlowSince = Date.now() - 60_000;
305
+
306
+ await manager.runQualityBudgetOnce();
307
+
308
+ assert.ok(
309
+ session.qualityAsk,
310
+ "a copy has no encoder to bound, so the only way to send fewer bits is another rendering of the film"
311
+ );
312
+ assert.ok(session.qualityAsk.height < 1080, `a step down (asked for ${session.qualityAsk?.height}p)`);
313
+ });
314
+
315
+ test("with two viewers the budget acts on the WORST link, not on whoever reported last", async (t) => {
316
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
317
+ t.after(async () => {
318
+ await manager.disposeAll();
319
+ await rm(dirPath, { recursive: true, force: true });
320
+ });
321
+
322
+ await produceSegments(session, 2_000_000);
323
+ // One viewer is comfortable and reported LAST, which under a single field was
324
+ // the whole of what the budget saw. The other cannot carry the stream and is
325
+ // running dry.
326
+ viewerOf(session, "thin").netReport = {
327
+ linkMbps: 1.0,
328
+ bufferedAheadSec: 1.5,
329
+ positionSeconds: 40,
330
+ at: Date.now() - 1_000
331
+ };
332
+ viewerOf(session, "fat").netReport = {
333
+ linkMbps: 80,
334
+ bufferedAheadSec: 60,
335
+ positionSeconds: 40,
336
+ at: Date.now()
337
+ };
338
+ session.linkSlowSince = Date.now() - 60_000;
339
+
340
+ await manager.runQualityBudgetOnce();
341
+
342
+ assert.ok(
343
+ session.qualityAsk,
344
+ "the viewer who cannot keep up decides, whichever of them reported most recently"
345
+ );
346
+ });
347
+
348
+ test("a report from a viewer who has left stops counting", async (t) => {
349
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
350
+ t.after(async () => {
351
+ await manager.disposeAll();
352
+ await rm(dirPath, { recursive: true, force: true });
353
+ });
354
+
355
+ await produceSegments(session, 2_000_000);
356
+ // Nothing releases a consumer when a data channel closes (roadmap item 55),
357
+ // so a departed viewer's last reading would otherwise go on deciding for the
358
+ // one still here. It is dropped on the next report rather than kept.
359
+ viewerOf(session, "gone").netReport = {
360
+ linkMbps: 1.0,
361
+ bufferedAheadSec: 1.5,
362
+ positionSeconds: 40,
363
+ at: Date.now() - 120_000
364
+ };
365
+ manager.recordNetReport(session.id, {
366
+ linkMbps: 80,
367
+ bufferedAheadSec: 60,
368
+ consumerId: "here",
369
+ positionSeconds: 40
370
+ });
371
+ session.linkSlowSince = Date.now() - 60_000;
372
+
373
+ await manager.runQualityBudgetOnce();
374
+
375
+ assert.equal(session.viewers.size, 1, "the stale entry was removed, not merely ignored");
376
+ assert.equal(session.qualityAsk, null, "the viewer who is here can carry the picture");
377
+ });
378
+
379
+ test("the way BACK UP exists, and a bitrate cap is lifted before the picture is enlarged", async (t) => {
380
+ const { manager, session, dirPath } = await managerWithSession();
381
+ t.after(async () => {
382
+ await manager.disposeAll();
383
+ await rm(dirPath, { recursive: true, force: true });
384
+ });
385
+
386
+ // The viewer is on 480p, the machine has been ahead of realtime for longer
387
+ // than the up window, and nothing is capping the bitrate.
388
+ session.variantHeight = 480;
389
+ session.encodeWidth = 854;
390
+ session.encodeHeight = 480;
391
+ session.recentSpeed = { speed: 2.4, at: Date.now(), run: [...session.runs][0] };
392
+ session.budgetUpSince = Date.now() - 120_000;
393
+
394
+ await manager.runQualityBudgetOnce();
395
+
396
+ assert.ok(session.qualityAsk, "for most of this project's life there was no step up at all");
397
+ assert.equal(
398
+ session.qualityAsk.height,
399
+ 540,
400
+ "one rung at a time: the lowest height above the one on screen, never above the source"
401
+ );
402
+ });
403
+
404
+ test("a capped picture gets its own bitrate back before it is asked to grow", async (t) => {
405
+ const { manager, session, dirPath } = await managerWithSession();
406
+ t.after(async () => {
407
+ await manager.disposeAll();
408
+ await rm(dirPath, { recursive: true, force: true });
409
+ });
410
+
411
+ session.variantHeight = 480;
412
+ session.encodeWidth = 854;
413
+ session.encodeHeight = 480;
414
+ session.rateCapKbps = 700;
415
+ session.recentSpeed = { speed: 2.4, at: Date.now(), run: [...session.runs][0] };
416
+ session.budgetUpSince = Date.now() - 120_000;
417
+ // A restart is what lifting the cap costs, and spawning ffmpeg is not this
418
+ // test's business. The run the fixture gave the session is the one the
419
+ // reading above came from, and replacing it here would make that reading
420
+ // belong to a run that is gone — which is exactly what the comparison is for.
421
+
422
+ await manager.runQualityBudgetOnce().catch(() => undefined);
423
+
424
+ assert.equal(session.rateCapKbps, null, "the cap goes first: it is cheaper than enlarging the picture");
425
+ assert.equal(
426
+ session.qualityAsk,
427
+ null,
428
+ "and the height is left for a second unbroken window, so the two do not move at once"
429
+ );
430
+ });
431
+
432
+ test("a stream that publishes no variants is left alone, and said so once", async (t) => {
433
+ const { manager, session, dirPath } = await managerWithSession({
434
+ transcodeVideo: false,
435
+ // A copy whose keyframe index could not be read falls back to an even grid
436
+ // ffmpeg does not cut on. Nothing can be aligned to that, so there is no
437
+ // master and no variant to move to.
438
+ cutGrid: "even"
439
+ });
440
+ t.after(async () => {
441
+ await manager.disposeAll();
442
+ await rm(dirPath, { recursive: true, force: true });
443
+ });
444
+
445
+ await produceSegments(session, 2_000_000);
446
+ viewerOf(session, "viewer").netReport = { linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: null, at: Date.now() };
447
+ session.linkSlowSince = Date.now() - 60_000;
448
+
449
+ await manager.runQualityBudgetOnce();
450
+
451
+ assert.equal(session.qualityAsk, null, "asking a player with no variants to change variant is nothing");
452
+ assert.equal(session.saidNoVariants, true, "and the reason is stated once, not once per window");
453
+ });
454
+
455
+ test("a height this machine has been MEASURED failing at is not what the way back up offers", async (t) => {
456
+ const { manager, session, dirPath } = await managerWithSession();
457
+ t.after(async () => {
458
+ await manager.disposeAll();
459
+ await rm(dirPath, { recursive: true, force: true });
460
+ });
461
+
462
+ // The base ran 720p at half realtime and the viewer was stepped down to 480p.
463
+ // The base's own height used to be exempt from every refusal it was the
464
+ // rung on screen, back when a step changed the encode inside it — so the way
465
+ // back up would have asked for 720p again, failed again, and stepped down
466
+ // again, about every hundred seconds for the length of the film.
467
+ manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 1e6 }];
468
+ session.lastAloneSpeed = 0.5;
469
+ session.variantHeight = 720;
470
+
471
+ const offered = manager.offeredHeights(session);
472
+
473
+ assert.ok(!offered.includes(720) || manager.liveOutputs.variantHeightOf(session) === 720);
474
+ // Now on the 480p variant: 720p has a reading of its own and must be gone.
475
+ session.variantHeight = 480;
476
+ session.encodeHeight = 480;
477
+ session.encodeWidth = 854;
478
+ assert.ok(
479
+ !manager.offeredHeights(session).includes(720),
480
+ "a rung measured below realtime is withdrawn once the viewer has left it"
481
+ );
482
+ });
483
+
484
+ test("a cap is not lifted because there is no higher rung to compare against", async (t) => {
485
+ const { manager, session, dirPath } = await managerWithSession();
486
+ t.after(async () => {
487
+ await manager.disposeAll();
488
+ await rm(dirPath, { recursive: true, force: true });
489
+ });
490
+
491
+ // At the top offered height, so there is no NEXT rung and the question of
492
+ // whether to lift the cap is about THIS one. Deciding it on "nothing to step
493
+ // to, so yes" took the cap off a link measured at a fifth of what the picture
494
+ // needs, after which #checkLinkBudget put it straight back: two ffmpeg
495
+ // restarts a minute and a half, on exactly the thin cellular viewer the cap
496
+ // exists for.
497
+ session.variantHeight = 1080;
498
+ session.encodeWidth = 1920;
499
+ session.encodeHeight = 1080;
500
+ session.rateCapKbps = 700;
501
+ session.recentSpeed = { speed: 2.4, at: Date.now(), run: [...session.runs][0] };
502
+ session.budgetUpSince = Date.now() - 120_000;
503
+ viewerOf(session, "viewer").netReport = { linkMbps: 1.0, bufferedAheadSec: 30, positionSeconds: null, at: Date.now() };
504
+
505
+ await manager.runQualityBudgetOnce();
506
+
507
+ assert.equal(session.rateCapKbps, 700, "the link still cannot carry this picture uncapped");
508
+ });