@torrent-tv/proxy 2.89.5 → 2.89.6

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.
@@ -1,753 +1,762 @@
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. The proxy asks only a viewer
15
- * in automatic mode, and the request travels only in that viewer's progress
16
- * report.
17
- */
18
-
19
- import test from "node:test";
20
- import { recordViewerReport } from "../services/viewer/report-intake.js";
21
- import { fakeProcess as fakeEncoder, measureSpeed, startRunOn } from "./helpers/encode-run.js";
22
- import assert from "node:assert/strict";
23
- import { SourceFile } from "../services/media/SourceFile.js";
24
- import { Timeline } from "../services/encode/output/Timeline.js";
25
- import { mkdir, rm, writeFile } from "node:fs/promises";
26
- import path from "node:path";
27
- import { managerWithOwnStore } from "./helpers/manager.js";
28
- import { Output } from "../services/encode/output/Output.js";
29
- import { qualityStateOf } from "../services/encode/quality/OutputQualityState.js";
30
- import { fmp4Format } from "../services/encode/segment-formats/fmp4.js";
31
- import { softwareDescriptor, maxrateKbpsFor, nominalKbpsFor } from "../services/encode/hwaccel.js";
32
- import { softwareRateControlFor } from "../services/encode/args.js";
33
- import { readVideoSampleSize } from "../services/encode/segment-formats/mp4-boxes.js";
34
- import { outputSpec } from "./helpers/output-spec.js";
35
-
36
- const BASE_ID = "aaaaaaaabbbbcccc";
37
- const SEGMENT_SECONDS = 4;
38
-
39
-
40
- /**
41
- * A session shaped like a live one, encoding 720p of a 1080p source.
42
- *
43
- * @param {{ dirPath: string, transcodeVideo?: boolean, cutGrid?: string }} params
44
- * `cutGrid` goes into the file's cut table; left out, it is what production
45
- * builds for this branch.
46
- * @returns {object}
47
- */
48
- function fakeSession({ dirPath, transcodeVideo = true, cutGrid = transcodeVideo ? "uniform" : "keyframe" }) {
49
- return {
50
- spec: outputSpec({ transcodeVideo, cutGrid }),
51
- id: BASE_ID,
52
- dirPath,
53
- // Where this file is cut, held by the file. A fixture that stated it
54
- // on the session was describing what production no longer does.
55
- //
56
- // The grid travels in here and nowhere else: a copy can only be cut where
57
- // the source already has a keyframe, so this is what decides whether the
58
- // stream publishes variants at all, and `#publishesVariants` reads it off
59
- // the table. The default is what production builds — a keyframe grid only
60
- // where one was read, which is the copy.
61
- timeline: new Timeline({
62
- boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
63
- cutGrid
64
- }),
65
- state: "ready",
66
- file: new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080, durationSeconds: 400 }),
67
- // An ordinary session reads its own file, and its sound is inside it. The
68
- // three differ only for a soundtrack shipped as a file of its own.
69
- get inputFile() { return this.file; },
70
- get audioFile() { return this.file; },
71
- startedAt: Date.now(),
72
- lastAccessedAt: Date.now(),
73
- runs: new Set(),
74
- runState: "running",
75
- runSerial: 1,
76
- lastError: "",
77
- consumers: new Set(),
78
- segmentFormat: fmp4Format,
79
- transcodeVideo,
80
- transcodeAudio: true,
81
- audioOnly: false,
82
- audioTrackIndex: 0,
83
- // The shape this output is encoded AS, decided once for the output.
84
- output: new Output({
85
- encodeWidth: transcodeVideo ? 1280 : 0,
86
- encodeHeight: transcodeVideo ? 720 : 0,
87
- outputFps: 24,
88
- softwarePreset: null,
89
- applyTonemap: false
90
- }),
91
- encodeRunGeneration: 0,
92
- usesExplicitCuts: false,
93
- useSyntheticPlaylist: true,
94
- playlistText: "#EXTM3U\n",
95
- progress: { state: "running", processedSeconds: 40, startPositionSeconds: 0 }
96
- };
97
- }
98
-
99
- /**
100
- * @param {{ transcodeVideo?: boolean, cutGrid?: string }} [options]
101
- * @returns {Promise<{ manager: object, session: object, dirPath: string, restarts: number[] }>}
102
- */
103
- async function managerWithSession({ transcodeVideo = true, cutGrid } = {}) {
104
- // Its own store root — see `helpers/manager.js` for what sharing one cost.
105
- const { manager } = managerWithOwnStore();
106
- // ADDRESSED THE WAY PRODUCTION ADDRESSES IT: a session's segments live in the
107
- // store's directory for its OUTPUT, and what it has produced is asked of the
108
- // store by that same key. A fixture with a directory of its own and no key
109
- // describes a proxy that no longer exists — the observed bitrate the link
110
- // budget reads would then be taken from files nothing can find.
111
- const outputKey = `auto-quality:fmt=fmp4:grid=${transcodeVideo ? "uniform" : "kf@0"}:video-only:v=0/${transcodeVideo ? "enc/libx264/1280x720@24/-/none/vbv=-" : "copy"}`;
112
- manager.segmentStore.useFormat(outputKey, fmp4Format);
113
- const dirPath = manager.segmentStore.directoryFor(outputKey);
114
- // A software host: the budget's own precondition.
115
- // A fully-downloaded file, so nothing here is ever read as download-bound —
116
- // the distinction is tested elsewhere and would only obscure these.
117
- manager.getSourceStats = async () => ({
118
- downloadSpeed: 10e6,
119
- fileProgress: 1,
120
- fileLength: 4e9
121
- });
122
- const session = fakeSession({ dirPath, transcodeVideo, cutGrid });
123
- session.outputKey = outputKey;
124
- manager.outputs.set(BASE_ID, session);
125
- manager.viewers.of(session, "viewer").qualityMode = "auto";
126
- // A run that states its speed, as every real one does from its first
127
- // seconds, and covers the whole film to its last segment, as the plan gives a
128
- // run: without a speed the plan cannot tell arrangements apart and takes the
129
- // encoder away, and with an open end it moves the run to a bounded one —
130
- // which starts a real ffmpeg in the output's directory, and on Windows that
131
- // directory then cannot be removed while the process lives.
132
- const run = startRunOn(session, { process: fakeEncoder(), speedX: 1, to: session.timeline.segmentCount - 1, producing: false });
133
- manager.encodeOrchestrator.adopt(outputKey, run);
134
- return { manager, session, dirPath };
135
- }
136
-
137
- /**
138
- * Produced segments of a known size, so the observed stream bitrate the link
139
- * check compares against is a real reading of real files.
140
- *
141
- * @param {object} session
142
- * @param {number} bytesEach
143
- * @returns {Promise<void>}
144
- */
145
- /**
146
- * This viewer's page reports a buffer that falls a second per second over two
147
- * segments' time, on the link named: what, on its trend, runs dry before
148
- * another output could have the piece they need (roadmap item 98).
149
- *
150
- * @param {object} viewer
151
- * @param {number} linkMbps
152
- * @returns {void}
153
- */
154
- function drainingReports(viewer, linkMbps) {
155
- const now = Date.now();
156
- for (const [ago, held] of [[8_000, 9], [4_000, 5], [0, 1.5]]) {
157
- viewer.report({ linkMbps, bufferedAheadSec: held, positionSeconds: 40, playing: true }, now - ago);
158
- }
159
- }
160
-
161
- /**
162
- * This viewer's page reports a buffer that grows, on the link named.
163
- *
164
- * @param {object} viewer
165
- * @param {number | null} linkMbps - Null when the page has not measured it.
166
- * @returns {void}
167
- */
168
- function fillingReports(viewer, linkMbps) {
169
- const now = Date.now();
170
- for (const [ago, held] of [[8_000, 40], [4_000, 50], [0, 60]]) {
171
- viewer.report({ linkMbps, bufferedAheadSec: held, positionSeconds: 40, playing: true }, now - ago);
172
- }
173
- }
174
-
175
- async function produceSegments(session, bytesEach) {
176
- // Where the run in force writes.
177
- const runDir = session.dirPath;
178
- await mkdir(runDir, { recursive: true });
179
- for (let index = 0; index < 4; index += 1) {
180
- await writeFile(
181
- path.join(runDir, session.segmentFormat.segmentFileName(index)),
182
- Buffer.alloc(bytesEach)
183
- );
184
- }
185
- }
186
-
187
- test("a picture that cannot be kept up with is asked for as another VARIANT, and its size is left alone", async (t) => {
188
- const { manager, session, dirPath } = await managerWithSession();
189
- t.after(async () => {
190
- await manager.lifecycle.disposeAll();
191
- // The store closes its watch on the directory as it drops the output, and
192
- // on Windows the directory stays held until the event loop has turned.
193
- await new Promise((resolve) => setImmediate(resolve));
194
- await rm(dirPath, { recursive: true, force: true });
195
- });
196
-
197
- const sizeBefore = `${session.encodeWidth}x${session.encodeHeight}`;
198
- // Below realtime over its own working time, and the viewer's buffer runs
199
- // dry on its trend although their link carries the stream.
200
- measureSpeed([...session.runs][0], 0.7);
201
- drainingReports(manager.viewers.get("viewer"), 80);
202
-
203
- await manager.quality.noteViewerReported(session.id, "viewer");
204
-
205
- assert.equal(
206
- `${session.encodeWidth}x${session.encodeHeight}`,
207
- sizeBefore,
208
- "the size the init segment describes must survive the step — that is the whole fault"
209
- );
210
- assert.ok(manager.viewers.get("viewer").qualityAsk, "the step is a request to the AUTO viewer to move variant");
211
- assert.ok(
212
- manager.viewers.get("viewer").qualityAsk.height < 720,
213
- `a step DOWN, and 720p was on screen (asked for ${manager.viewers.get("viewer").qualityAsk?.height}p)`
214
- );
215
- });
216
-
217
- test("a manual viewer is never sent an automatic quality request", async (t) => {
218
- const { manager, session, dirPath } = await managerWithSession();
219
- t.after(async () => {
220
- await manager.lifecycle.disposeAll();
221
- // The store closes its watch on the directory as it drops the output, and
222
- // on Windows the directory stays held until the event loop has turned.
223
- await new Promise((resolve) => setImmediate(resolve));
224
- await rm(dirPath, { recursive: true, force: true });
225
- });
226
- manager.viewers.get("viewer").qualityMode = "manual";
227
- measureSpeed([...session.runs][0], 0.7);
228
- drainingReports(manager.viewers.get("viewer"), 80);
229
-
230
- await manager.quality.noteViewerReported(session.id, "viewer");
231
-
232
- assert.equal(manager.viewers.get("viewer").qualityAsk, null);
233
- const progress = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
234
- assert.equal(progress.requestedHeight, 0);
235
- });
236
-
237
- test("the request reaches the browser in the progress report, and stops once the viewer is there", async (t) => {
238
- const { manager, session, dirPath } = await managerWithSession();
239
- t.after(async () => {
240
- await manager.lifecycle.disposeAll();
241
- // The store closes its watch on the directory as it drops the output, and
242
- // on Windows the directory stays held until the event loop has turned.
243
- await new Promise((resolve) => setImmediate(resolve));
244
- await rm(dirPath, { recursive: true, force: true });
245
- });
246
-
247
- manager.viewers.get("viewer").qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
248
- const asked = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
249
- assert.equal(asked.requestedHeight, 480, "the request travels with every progress report");
250
-
251
- // The player moved: the variant it is now watching IS the height asked for.
252
- session.variantHeight = 480;
253
- const answered = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
254
- assert.equal(answered.requestedHeight, 0, "a request the viewer has answered is not repeated");
255
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "and it is let go of, not merely hidden");
256
- });
257
-
258
- test("a request stands while its conditions hold, and the next report that does not ask for it lets it go", async (t) => {
259
- const { manager, session, dirPath } = await managerWithSession();
260
- t.after(async () => {
261
- await manager.lifecycle.disposeAll();
262
- // The store closes its watch on the directory as it drops the output, and
263
- // on Windows the directory stays held until the event loop has turned.
264
- await new Promise((resolve) => setImmediate(resolve));
265
- await rm(dirPath, { recursive: true, force: true });
266
- });
267
-
268
- // Asked when their buffer was running dry; no chosen time ends it.
269
- manager.viewers.get("viewer").qualityAsk = { height: 480, at: Date.now() - 120_000, reason: "measured" };
270
- const standing = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
271
- assert.equal(standing.requestedHeight, 480, "two minutes on, it still stands: nothing has said otherwise");
272
-
273
- // Their next report shows a buffer that grows: what it was asked for is gone.
274
- // The machine has no room to spare, so nothing else is asked in its place.
275
- measureSpeed([...session.runs][0], 0.9);
276
- fillingReports(manager.viewers.get("viewer"), null);
277
- await manager.quality.noteViewerReported(session.id, "viewer");
278
-
279
- const progress = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
280
- assert.equal(progress.requestedHeight, 0);
281
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "let go by the judgement that did not repeat it");
282
- });
283
-
284
- test("a request the next report asks for again stands", async (t) => {
285
- const { manager, session, dirPath } = await managerWithSession();
286
- t.after(async () => {
287
- await manager.lifecycle.disposeAll();
288
- await new Promise((resolve) => setImmediate(resolve));
289
- await rm(dirPath, { recursive: true, force: true });
290
- });
291
- measureSpeed([...session.runs][0], 0.7);
292
- drainingReports(manager.viewers.get("viewer"), 80);
293
- await manager.quality.noteViewerReported(session.id, "viewer");
294
- const asked = manager.viewers.get("viewer").qualityAsk;
295
- assert.ok(asked, "the machine cannot keep up and the buffer runs dry");
296
-
297
- drainingReports(manager.viewers.get("viewer"), 80);
298
- await manager.quality.noteViewerReported(session.id, "viewer");
299
-
300
- assert.equal(manager.viewers.get("viewer").qualityAsk, asked, "the same request, not let go and not made again");
301
- });
302
-
303
- test("a COPIED picture is never asked to slow its encoder, because it has none", async (t) => {
304
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
305
- t.after(async () => {
306
- await manager.lifecycle.disposeAll();
307
- // The store closes its watch on the directory as it drops the output, and
308
- // on Windows the directory stays held until the event loop has turned.
309
- await new Promise((resolve) => setImmediate(resolve));
310
- await rm(dirPath, { recursive: true, force: true });
311
- });
312
-
313
- // Whatever this reading says, a copy has no encoder to make cheaper: moving
314
- // the viewer to a RE-ENCODED rung costs the machine more, not less.
315
- measureSpeed([...session.runs][0], 0.4);
316
- drainingReports(manager.viewers.get("viewer"), 80);
317
-
318
- await manager.quality.noteViewerReported(session.id, "viewer");
319
-
320
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "the copy path's lever is the viewer's link, not the CPU");
321
- });
322
-
323
- test("the output's own rate control is what reaches ffmpeg, and nothing about the size moves with it", () => {
324
- // Two limits are two outputs (roadmap item 97, step 10): the figures are
325
- // read off the output's identity and handed to the encoder as they are. The
326
- // level is the nominal output's, so every limit at one size declares the
327
- // same one.
328
- const nominal = softwareRateControlFor({ width: 1280, height: 720, fps: 24 });
329
- const lower = softwareRateControlFor({ width: 1280, height: 720, fps: 24, capKbps: 1200 });
330
- const build = (rateControl) => softwareDescriptor().buildVideoArgs({
331
- targetWidth: 1280,
332
- targetHeight: 720,
333
- segmentDurationSec: 4,
334
- fps: 24,
335
- rateControl
336
- });
337
- const atNominal = build(nominal);
338
- const atLower = build(lower);
339
-
340
- assert.equal(atNominal[atNominal.indexOf("-maxrate") + 1], `${maxrateKbpsFor(nominalKbpsFor({ width: 1280, height: 720 }))}k`);
341
- assert.equal(atLower[atLower.indexOf("-maxrate") + 1], `${maxrateKbpsFor(1200)}k`);
342
- assert.equal(lower.level, nominal.level, "a lower limit is declared at the nominal output's level");
343
- assert.equal(atLower[atLower.indexOf("-level:v") + 1], nominal.level);
344
- assert.deepEqual(
345
- atNominal.slice(0, atNominal.indexOf("-maxrate")),
346
- atLower.slice(0, atLower.indexOf("-maxrate")),
347
- "the scale filter, the codec and the preset are untouched by the limit"
348
- );
349
- assert.equal(build(null).includes("-maxrate"), false, "an output that states no limit is given none");
350
- assert.throws(
351
- () => softwareRateControlFor({ width: 1280, height: 720, fps: 24, capKbps: nominalKbpsFor({ width: 1280, height: 720 }) + 1 }),
352
- RangeError,
353
- "a limit above the size's own is refused, not lowered"
354
- );
355
- });
356
-
357
- test("the size an init segment describes is read from the init, not assumed", () => {
358
- // A minimal moov/trak/mdia/minf/stbl/stsd with one avc1 entry. Built here
359
- // rather than taken from a fixture so the offsets under test are the ones
360
- // ISO/IEC 14496-12 states, and a fixture cannot quietly encode a mistake.
361
- const avc1 = Buffer.alloc(8 + 8 + 16 + 4);
362
- avc1.writeUInt32BE(avc1.length, 0);
363
- avc1.write("avc1", 4, "latin1");
364
- avc1.writeUInt16BE(960, 32);
365
- avc1.writeUInt16BE(540, 34);
366
-
367
- const stsd = Buffer.concat([Buffer.alloc(8 + 8), avc1]);
368
- stsd.writeUInt32BE(stsd.length, 0);
369
- stsd.write("stsd", 4, "latin1");
370
- stsd.writeUInt32BE(1, 12); // entry_count
371
-
372
- const wrap = (type, payload) => {
373
- const box = Buffer.alloc(8 + payload.length);
374
- box.writeUInt32BE(box.length, 0);
375
- box.write(type, 4, "latin1");
376
- payload.copy(box, 8);
377
- return box;
378
- };
379
- const init = wrap("moov", wrap("trak", wrap("mdia", wrap("minf", wrap("stbl", stsd)))));
380
-
381
- assert.deepEqual(readVideoSampleSize(init), { width: 960, height: 540 });
382
- assert.equal(readVideoSampleSize(Buffer.alloc(0)), null);
383
- });
384
-
385
- test("a COPIED picture too thick for the viewer's link is asked for as a smaller VARIANT", async (t) => {
386
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
387
- t.after(async () => {
388
- await manager.lifecycle.disposeAll();
389
- // The store closes its watch on the directory as it drops the output, and
390
- // on Windows the directory stays held until the event loop has turned.
391
- await new Promise((resolve) => setImmediate(resolve));
392
- await rm(dirPath, { recursive: true, force: true });
393
- });
394
-
395
- // Four seconds of segment at 2 MB is ~4 Mbit/s of stream. The viewer reports
396
- // a link that cannot carry it and a buffer that is running dry.
397
- await produceSegments(session, 2_000_000);
398
- drainingReports(manager.viewers.of(session, "viewer"), 1.0);
399
-
400
- await manager.quality.noteViewerReported(session.id, "viewer");
401
-
402
- assert.ok(
403
- manager.viewers.get("viewer").qualityAsk,
404
- "a copy has no encoder to bound, so the only way to send fewer bits is another rendering of the film"
405
- );
406
- assert.equal(manager.viewers.get("viewer").qualityAsk.urgent, true, "their buffer runs dry first: no cushion is waited for");
407
- assert.ok(manager.viewers.get("viewer").qualityAsk.height < 1080, `a step down (asked for ${manager.viewers.get("viewer").qualityAsk?.height}p)`);
408
- });
409
-
410
- test("with two viewers each link decides for its own viewer, not the worst for both", async (t) => {
411
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
412
- t.after(async () => {
413
- await manager.lifecycle.disposeAll();
414
- // The store closes its watch on the directory as it drops the output, and
415
- // on Windows the directory stays held until the event loop has turned.
416
- await new Promise((resolve) => setImmediate(resolve));
417
- await rm(dirPath, { recursive: true, force: true });
418
- });
419
-
420
- await produceSegments(session, 2_000_000);
421
- // One viewer is comfortable and reported LAST, which under a single field was
422
- // the whole of what the budget saw. The other cannot carry the stream and is
423
- // running dry.
424
- manager.viewers.of(session, "thin").qualityMode = "auto";
425
- drainingReports(manager.viewers.of(session, "thin"), 1.0);
426
- manager.viewers.of(session, "fat").qualityMode = "auto";
427
- fillingReports(manager.viewers.of(session, "fat"), 80);
428
-
429
- await manager.quality.noteViewerReported(session.id, "thin");
430
- await manager.quality.noteViewerReported(session.id, "fat");
431
-
432
- assert.ok(
433
- manager.viewers.get("thin").qualityAsk,
434
- "the viewer who cannot keep up is asked, whichever of them reported most recently"
435
- );
436
- assert.equal(
437
- manager.viewers.get("fat").qualityAsk,
438
- null,
439
- "and ONLY them: a thin link is its owner's, and the viewer beside them keeps their picture"
440
- );
441
- });
442
-
443
- test("a reading stops counting when the person leaves, not when it gets old", async (t) => {
444
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
445
- t.after(async () => {
446
- await manager.lifecycle.disposeAll();
447
- // The store closes its watch on the directory as it drops the output, and
448
- // on Windows the directory stays held until the event loop has turned.
449
- await new Promise((resolve) => setImmediate(resolve));
450
- await rm(dirPath, { recursive: true, force: true });
451
- });
452
-
453
- await produceSegments(session, 2_000_000);
454
- // A LINK READING DOES NOT EXPIRE. It is the last thing known about that link,
455
- // and how fast a link is does not change because nobody measured it for a
456
- // minute — the page keeps its own last figure for the same reason. What ends
457
- // a reading is the person leaving, which is presence, and presence is the
458
- // connection: silence removes nobody (2026-09-05, a soundtrack's encoder
459
- // stopped because those two questions had one answer).
460
- const gone = manager.viewers.of(session, "gone");
461
- gone.qualityMode = "auto";
462
- gone.report({ linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: 40, playing: true }, Date.now() - 120_000);
463
- gone.gone = true;
464
- recordViewerReport({
465
- outputs: manager.outputs,
466
- viewers: manager.viewers,
467
- sessionId: session.id,
468
- report: { linkMbps: 80, bufferedAheadSec: 60, consumerId: "here", positionSeconds: 40 }
469
- });
470
- manager.viewers.get("here").qualityMode = "auto";
471
-
472
- await manager.quality.noteViewerReported(session.id, "here");
473
-
474
- assert.equal(manager.viewers.forOutput(session).size, 3, "the viewer is still known — silence is not leaving");
475
- // Their reading is not deleted anywhere: it is simply not theirs to give any
476
- // more, because they are not here. Nothing walks it for a decision.
477
- assert.equal(
478
- manager.viewers.get("gone").linkReading()?.linkMbps,
479
- 1.0,
480
- "their last reading stands as the last thing known about that link"
481
- );
482
- assert.equal(manager.viewers.get("here").qualityAsk, null, "the viewer who is here can carry the picture");
483
- });
484
-
485
- test("the way BACK UP exists, one rung at a time", async (t) => {
486
- const { manager, session, dirPath } = await managerWithSession();
487
- t.after(async () => {
488
- await manager.lifecycle.disposeAll();
489
- // The store closes its watch on the directory as it drops the output, and
490
- // on Windows the directory stays held until the event loop has turned.
491
- await new Promise((resolve) => setImmediate(resolve));
492
- await rm(dirPath, { recursive: true, force: true });
493
- });
494
-
495
- // The viewer is on 480p, the machine makes it ahead of realtime over its own
496
- // working time, and their buffer grows and holds more than another output
497
- // takes to be ready. No window has to pass: every term is measured.
498
- session.variantHeight = 480;
499
- session.encodeWidth = 854;
500
- session.encodeHeight = 480;
501
- measureSpeed([...session.runs][0], 2.4);
502
- // Their link is not measured here: what is under test is the room, and a
503
- // measured link would also weigh a soundtrack this fixture states no rate for.
504
- fillingReports(manager.viewers.get("viewer"), null);
505
-
506
- await manager.quality.noteViewerReported(session.id, "viewer");
507
-
508
- assert.ok(manager.viewers.get("viewer").qualityAsk, "for most of this project's life there was no step up at all");
509
- assert.equal(
510
- manager.viewers.get("viewer").qualityAsk.height,
511
- 540,
512
- "one rung at a time: the lowest height above the one on screen, never above the source"
513
- );
514
- });
515
-
516
- test("a re-encoded picture too thick for the viewer's link is asked for as a smaller VARIANT, and its output is left as it is", async (t) => {
517
- // The limit on a picture's bitrate is part of the output now, so a thin link
518
- // no longer lowers the limit of the output every viewer of it is watching.
519
- // Until each viewer is served an output of their own (roadmap item 97, steps
520
- // 11-12), the one lever is a lower height, asked of a viewer in AUTO.
521
- const { manager, session, dirPath } = await managerWithSession();
522
- t.after(async () => {
523
- await manager.lifecycle.disposeAll();
524
- // The store closes its watch on the directory as it drops the output, and
525
- // on Windows the directory stays held until the event loop has turned.
526
- await new Promise((resolve) => setImmediate(resolve));
527
- await rm(dirPath, { recursive: true, force: true });
528
- });
529
- const keyBefore = session.outputKey;
530
-
531
- await produceSegments(session, 2_000_000);
532
- manager.viewers.of(session, "viewer").qualityMode = "auto";
533
- drainingReports(manager.viewers.of(session, "viewer"), 1.0);
534
-
535
- await manager.quality.noteViewerReported(session.id, "viewer");
536
-
537
- assert.ok(manager.viewers.get("viewer").qualityAsk, "the viewer is asked to move to a smaller variant");
538
- assert.equal(session.outputKey, keyBefore, "and the output they were on is not altered under anybody");
539
- });
540
-
541
- test("a stream that publishes no variants is left alone, and said so once", async (t) => {
542
- const { manager, session, dirPath } = await managerWithSession({
543
- transcodeVideo: false,
544
- // A copy whose keyframe index could not be read falls back to an even grid
545
- // ffmpeg does not cut on. Nothing can be aligned to that, so there is no
546
- // master and no variant to move to.
547
- cutGrid: "even"
548
- });
549
- t.after(async () => {
550
- await manager.lifecycle.disposeAll();
551
- // The store closes its watch on the directory as it drops the output, and
552
- // on Windows the directory stays held until the event loop has turned.
553
- await new Promise((resolve) => setImmediate(resolve));
554
- await rm(dirPath, { recursive: true, force: true });
555
- });
556
-
557
- await produceSegments(session, 2_000_000);
558
- drainingReports(manager.viewers.of(session, "viewer"), 1.0);
559
-
560
- await manager.quality.noteViewerReported(session.id, "viewer");
561
-
562
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "asking a player with no variants to change variant is nothing");
563
- assert.equal(qualityStateOf(session).saidNoVariants, true, "and the reason is stated once, not once per window");
564
- });
565
-
566
- test("a height this machine has been MEASURED failing at is not what the way back up offers", async (t) => {
567
- const { manager, session, dirPath } = await managerWithSession();
568
- t.after(async () => {
569
- await manager.lifecycle.disposeAll();
570
- // The store closes its watch on the directory as it drops the output, and
571
- // on Windows the directory stays held until the event loop has turned.
572
- await new Promise((resolve) => setImmediate(resolve));
573
- await rm(dirPath, { recursive: true, force: true });
574
- });
575
-
576
- // The base ran 720p at half realtime and the viewer was stepped down to 480p.
577
- // The base's own height used to be exempt from every refusal — it was the
578
- // rung on screen, back when a step changed the encode inside it — so the way
579
- // back up would have asked for 720p again, failed again, and stepped down
580
- // again, about every hundred seconds for the length of the film.
581
- manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 1e6 }];
582
- qualityStateOf(session).lastAloneSpeed = 0.5;
583
- session.variantHeight = 720;
584
-
585
- const offered = manager.quality.offeredHeights(session);
586
-
587
- assert.ok(!offered.includes(720) || manager.outputs.variantHeightOf(session) === 720);
588
- // Now on the 480p variant: 720p has a reading of its own and must be gone.
589
- session.variantHeight = 480;
590
- session.encodeHeight = 480;
591
- session.encodeWidth = 854;
592
- assert.ok(
593
- !manager.quality.offeredHeights(session).includes(720),
594
- "a rung measured below realtime is withdrawn once the viewer has left it"
595
- );
596
- });
597
-
598
- test("a request is answered when the viewers watching are on that height, whoever they are", async (t) => {
599
- const { manager, session, dirPath } = await managerWithSession();
600
- t.after(async () => {
601
- await manager.lifecycle.disposeAll();
602
- // The store closes its watch on the directory as it drops the output, and
603
- // on Windows the directory stays held until the event loop has turned.
604
- await new Promise((resolve) => setImmediate(resolve));
605
- await rm(dirPath, { recursive: true, force: true });
606
- });
607
- // A named viewer followed the request to a 480p step. The step is an output
608
- // of its own; the picture's own height is still 720.
609
- const stepId = "aaaaaaaabbbbdddd";
610
- const step = { ...fakeSession({ dirPath }), id: stepId, isStep: true, variantHeight: 480 };
611
- step.outputKey = `${session.outputKey}:step480`;
612
- manager.outputs.set(stepId, step);
613
- manager.outputs.markStep(step);
614
- manager.viewers.of(session, "alice").qualityMode = "auto";
615
- manager.viewers.of(session, "alice").activeVariantId = stepId;
616
-
617
- manager.viewers.get("alice").qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
618
- const answered = await manager.viewerRequests.getSessionProgress(BASE_ID, "alice");
619
-
620
- assert.equal(answered.requestedHeight, 0, "the viewer is on the height asked for");
621
- assert.equal(manager.viewers.get("alice").qualityAsk, null, "so the request is let go of");
622
- });
623
-
624
- test("a thin link whose buffer is filling moves nothing: the trend, not the reading, decides", async (t) => {
625
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
626
- t.after(async () => {
627
- await manager.lifecycle.disposeAll();
628
- // The store closes its watch on the directory as it drops the output, and
629
- // on Windows the directory stays held until the event loop has turned.
630
- await new Promise((resolve) => setImmediate(resolve));
631
- await rm(dirPath, { recursive: true, force: true });
632
- });
633
- await produceSegments(session, 2_000_000);
634
- fillingReports(manager.viewers.of(session, "viewer"), 1.0);
635
-
636
- await manager.quality.noteViewerReported(session.id, "viewer");
637
-
638
- assert.equal(manager.viewers.get("viewer").qualityAsk, null);
639
- });
640
-
641
- test("a step up being prepared is dropped once the viewer's buffer starts running dry", async (t) => {
642
- const { manager, session, dirPath } = await managerWithSession();
643
- t.after(async () => {
644
- await manager.lifecycle.disposeAll();
645
- // The store closes its watch on the directory as it drops the output, and
646
- // on Windows the directory stays held until the event loop has turned.
647
- await new Promise((resolve) => setImmediate(resolve));
648
- await rm(dirPath, { recursive: true, force: true });
649
- });
650
- session.variantHeight = 480;
651
- await produceSegments(session, 200_000);
652
- const viewer = manager.viewers.get("viewer");
653
- viewer.askQuality(540, "room to spare", Date.now());
654
- drainingReports(viewer, 80);
655
-
656
- await manager.quality.noteViewerReported(session.id, "viewer");
657
-
658
- assert.equal(viewer.qualityAsk, null, "the conditions it was asked under have gone back");
659
- });
660
-
661
- test("a picture seen larger than the rung on screen is asked one rung up, when there is room", async (t) => {
662
- const { manager, session, dirPath } = await managerWithSession();
663
- t.after(async () => {
664
- await manager.lifecycle.disposeAll();
665
- // The store closes its watch on the directory as it drops the output, and
666
- // on Windows the directory stays held until the event loop has turned.
667
- await new Promise((resolve) => setImmediate(resolve));
668
- await rm(dirPath, { recursive: true, force: true });
669
- });
670
- session.variantHeight = 480;
671
- session.encodeWidth = 854;
672
- session.encodeHeight = 480;
673
- measureSpeed([...session.runs][0], 2.4);
674
- manager.viewers.get("viewer").noteVisiblePicture({ width: 1920, height: 1080 });
675
- fillingReports(manager.viewers.get("viewer"), null);
676
-
677
- await manager.quality.noteViewerReported(session.id, "viewer");
678
-
679
- assert.equal(manager.viewers.get("viewer").qualityAsk?.height, 540);
680
- assert.equal(manager.viewers.get("viewer").qualityAsk?.urgent, false, "a step up waits for the cushion");
681
- });
682
-
683
- test("a picture seen smaller than the rung on screen moves nothing until a rung of its height is ready", async (t) => {
684
- const { manager, session, dirPath } = await managerWithSession();
685
- t.after(async () => {
686
- await manager.lifecycle.disposeAll();
687
- // The store closes its watch on the directory as it drops the output, and
688
- // on Windows the directory stays held until the event loop has turned.
689
- await new Promise((resolve) => setImmediate(resolve));
690
- await rm(dirPath, { recursive: true, force: true });
691
- });
692
- manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
693
-
694
- await manager.quality.noteViewerReported(session.id, "viewer");
695
-
696
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "no 360p rung is made yet; nothing is started for this alone");
697
- });
698
-
699
- test("a COPY taller than the picture seen is left alone", async (t) => {
700
- const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
701
- t.after(async () => {
702
- await manager.lifecycle.disposeAll();
703
- // The store closes its watch on the directory as it drops the output, and
704
- // on Windows the directory stays held until the event loop has turned.
705
- await new Promise((resolve) => setImmediate(resolve));
706
- await rm(dirPath, { recursive: true, force: true });
707
- });
708
- manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
709
- // Every smaller rung is ready for them: what stops the move is the rule
710
- // about copies, and nothing else.
711
- manager.renditions.heightReadyFor = () => true;
712
-
713
- await manager.quality.noteViewerReported(session.id, "viewer");
714
-
715
- assert.equal(manager.viewers.get("viewer").qualityAsk, null, "a copy is never re-encoded for being taller than the screen");
716
- });
717
-
718
- test("a step down for the machine goes to the rung the picture seen bounds, where that is lower", async (t) => {
719
- const { manager, session, dirPath } = await managerWithSession();
720
- t.after(async () => {
721
- await manager.lifecycle.disposeAll();
722
- // The store closes its watch on the directory as it drops the output, and
723
- // on Windows the directory stays held until the event loop has turned.
724
- await new Promise((resolve) => setImmediate(resolve));
725
- await rm(dirPath, { recursive: true, force: true });
726
- });
727
- manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
728
- measureSpeed([...session.runs][0], 0.7);
729
- drainingReports(manager.viewers.get("viewer"), 80);
730
-
731
- await manager.quality.noteViewerReported(session.id, "viewer");
732
-
733
- const asked = manager.viewers.get("viewer").qualityAsk?.height;
734
- assert.ok(asked, "the machine cannot keep up: a step down is asked");
735
- assert.ok(asked <= 360, `not a rung between that the screen cannot show (asked for ${asked}p)`);
736
- });
737
-
738
- test("a machine below realtime whose viewer's buffer is filling moves nothing", async (t) => {
739
- const { manager, session, dirPath } = await managerWithSession();
740
- t.after(async () => {
741
- await manager.lifecycle.disposeAll();
742
- await new Promise((resolve) => setImmediate(resolve));
743
- await rm(dirPath, { recursive: true, force: true });
744
- });
745
- // What the cushion already holds covers the shortfall: no chosen window of
746
- // slowness decides, the viewer's own buffer trend does.
747
- measureSpeed([...session.runs][0], 0.7);
748
- fillingReports(manager.viewers.get("viewer"), 80);
749
-
750
- await manager.quality.noteViewerReported(session.id, "viewer");
751
-
752
- assert.ok(!(manager.viewers.get("viewer").qualityAsk?.height < 720), "no step down while the buffer grows");
753
- });
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. The proxy asks only a viewer
15
+ * in automatic mode, and the request travels only in that viewer's progress
16
+ * report.
17
+ */
18
+
19
+ import test from "node:test";
20
+ import { recordViewerReport } from "../services/viewer/report-intake.js";
21
+ import { fakeProcess as fakeEncoder, measureSpeed, startRunOn } from "./helpers/encode-run.js";
22
+ import assert from "node:assert/strict";
23
+ import { SourceFile } from "../services/media/SourceFile.js";
24
+ import { Timeline } from "../services/encode/output/Timeline.js";
25
+ import { mkdir, rm, writeFile } from "node:fs/promises";
26
+ import path from "node:path";
27
+ import { managerWithOwnStore } from "./helpers/manager.js";
28
+ import { Output } from "../services/encode/output/Output.js";
29
+ import { qualityStateOf } from "../services/encode/quality/OutputQualityState.js";
30
+ import { fmp4Format } from "../services/encode/segment-formats/fmp4.js";
31
+ import { softwareDescriptor, maxrateKbpsFor, nominalKbpsFor } from "../services/encode/hwaccel.js";
32
+ import { softwareRateControlFor } from "../services/encode/args.js";
33
+ import { readVideoSampleSize } from "../services/encode/segment-formats/mp4-boxes.js";
34
+ import { outputSpec } from "./helpers/output-spec.js";
35
+
36
+ const BASE_ID = "aaaaaaaabbbbcccc";
37
+ const SEGMENT_SECONDS = 4;
38
+
39
+
40
+ /**
41
+ * A session shaped like a live one, encoding 720p of a 1080p source.
42
+ *
43
+ * @param {{ dirPath: string, transcodeVideo?: boolean, cutGrid?: string }} params
44
+ * `cutGrid` goes into the file's cut table; left out, it is what production
45
+ * builds for this branch.
46
+ * @returns {object}
47
+ */
48
+ function fakeSession({ dirPath, transcodeVideo = true, cutGrid = transcodeVideo ? "uniform" : "keyframe" }) {
49
+ return {
50
+ spec: outputSpec({ transcodeVideo, cutGrid }),
51
+ id: BASE_ID,
52
+ dirPath,
53
+ // Where this file is cut, held by the file. A fixture that stated it
54
+ // on the session was describing what production no longer does.
55
+ //
56
+ // The grid travels in here and nowhere else: a copy can only be cut where
57
+ // the source already has a keyframe, so this is what decides whether the
58
+ // stream publishes variants at all, and `#publishesVariants` reads it off
59
+ // the table. The default is what production builds — a keyframe grid only
60
+ // where one was read, which is the copy.
61
+ timeline: new Timeline({
62
+ boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
63
+ cutGrid
64
+ }),
65
+ state: "ready",
66
+ file: new SourceFile({ sourceKey: "source-1", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080, durationSeconds: 400 }),
67
+ // An ordinary session reads its own file, and its sound is inside it. The
68
+ // three differ only for a soundtrack shipped as a file of its own.
69
+ get inputFile() { return this.file; },
70
+ get audioFile() { return this.file; },
71
+ startedAt: Date.now(),
72
+ lastAccessedAt: Date.now(),
73
+ runs: new Set(),
74
+ runState: "running",
75
+ runSerial: 1,
76
+ lastError: "",
77
+ consumers: new Set(),
78
+ segmentFormat: fmp4Format,
79
+ transcodeVideo,
80
+ transcodeAudio: true,
81
+ audioOnly: false,
82
+ audioTrackIndex: 0,
83
+ // The shape this output is encoded AS, decided once for the output.
84
+ output: new Output({
85
+ encodeWidth: transcodeVideo ? 1280 : 0,
86
+ encodeHeight: transcodeVideo ? 720 : 0,
87
+ outputFps: 24,
88
+ softwarePreset: null,
89
+ applyTonemap: false
90
+ }),
91
+ encodeRunGeneration: 0,
92
+ usesExplicitCuts: false,
93
+ useSyntheticPlaylist: true,
94
+ playlistText: "#EXTM3U\n",
95
+ progress: { state: "running", processedSeconds: 40, startPositionSeconds: 0 }
96
+ };
97
+ }
98
+
99
+ /**
100
+ * @param {{ transcodeVideo?: boolean, cutGrid?: string, softwarePresetBenchmark?: object[] }} [options]
101
+ * `softwarePresetBenchmark` is the host's startup measurement, read through
102
+ * the encoder in use and not assigned afterwards.
103
+ * @returns {Promise<{ manager: object, session: object, dirPath: string, restarts: number[] }>}
104
+ */
105
+ async function managerWithSession({ transcodeVideo = true, cutGrid, softwarePresetBenchmark } = {}) {
106
+ // Its own store root — see `helpers/manager.js` for what sharing one cost.
107
+ const { manager } = managerWithOwnStore({ softwarePresetBenchmark });
108
+ // ADDRESSED THE WAY PRODUCTION ADDRESSES IT: a session's segments live in the
109
+ // store's directory for its OUTPUT, and what it has produced is asked of the
110
+ // store by that same key. A fixture with a directory of its own and no key
111
+ // describes a proxy that no longer exists — the observed bitrate the link
112
+ // budget reads would then be taken from files nothing can find.
113
+ const outputKey = `auto-quality:fmt=fmp4:grid=${transcodeVideo ? "uniform" : "kf@0"}:video-only:v=0/${transcodeVideo ? "enc/libx264/1280x720@24/-/none/vbv=-" : "copy"}`;
114
+ manager.segmentStore.useFormat(outputKey, fmp4Format);
115
+ const dirPath = manager.segmentStore.directoryFor(outputKey);
116
+ // A software host: the budget's own precondition.
117
+ // A fully-downloaded file, so nothing here is ever read as download-bound —
118
+ // the distinction is tested elsewhere and would only obscure these.
119
+ manager.getSourceStats = async () => ({
120
+ downloadSpeed: 10e6,
121
+ fileProgress: 1,
122
+ fileLength: 4e9
123
+ });
124
+ const session = fakeSession({ dirPath, transcodeVideo, cutGrid });
125
+ session.outputKey = outputKey;
126
+ manager.outputs.set(BASE_ID, session);
127
+ manager.viewers.of(session, "viewer").qualityMode = "auto";
128
+ // A run that states its speed, as every real one does from its first
129
+ // seconds, and covers the whole film to its last segment, as the plan gives a
130
+ // run: without a speed the plan cannot tell arrangements apart and takes the
131
+ // encoder away, and with an open end it moves the run to a bounded one —
132
+ // which starts a real ffmpeg in the output's directory, and on Windows that
133
+ // directory then cannot be removed while the process lives.
134
+ const run = startRunOn(session, { process: fakeEncoder(), speedX: 1, to: session.timeline.segmentCount - 1, producing: false });
135
+ manager.encodeOrchestrator.adopt(outputKey, run);
136
+ return { manager, session, dirPath };
137
+ }
138
+
139
+ /**
140
+ * Produced segments of a known size, so the observed stream bitrate the link
141
+ * check compares against is a real reading of real files.
142
+ *
143
+ * @param {object} session
144
+ * @param {number} bytesEach
145
+ * @returns {Promise<void>}
146
+ */
147
+ /**
148
+ * This viewer's page reports a buffer that falls a second per second over two
149
+ * segments' time, on the link named: what, on its trend, runs dry before
150
+ * another output could have the piece they need (roadmap item 98).
151
+ *
152
+ * @param {object} viewer
153
+ * @param {number} linkMbps
154
+ * @returns {void}
155
+ */
156
+ function drainingReports(viewer, linkMbps) {
157
+ const now = Date.now();
158
+ for (const [ago, held] of [[8_000, 9], [4_000, 5], [0, 1.5]]) {
159
+ viewer.report({ linkMbps, bufferedAheadSec: held, positionSeconds: 40, playing: true }, now - ago);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * This viewer's page reports a buffer that grows, on the link named.
165
+ *
166
+ * @param {object} viewer
167
+ * @param {number | null} linkMbps - Null when the page has not measured it.
168
+ * @returns {void}
169
+ */
170
+ function fillingReports(viewer, linkMbps) {
171
+ const now = Date.now();
172
+ for (const [ago, held] of [[8_000, 40], [4_000, 50], [0, 60]]) {
173
+ viewer.report({ linkMbps, bufferedAheadSec: held, positionSeconds: 40, playing: true }, now - ago);
174
+ }
175
+ }
176
+
177
+ async function produceSegments(session, bytesEach) {
178
+ // Where the run in force writes.
179
+ const runDir = session.dirPath;
180
+ await mkdir(runDir, { recursive: true });
181
+ for (let index = 0; index < 4; index += 1) {
182
+ await writeFile(
183
+ path.join(runDir, session.segmentFormat.segmentFileName(index)),
184
+ Buffer.alloc(bytesEach)
185
+ );
186
+ }
187
+ }
188
+
189
+ test("a picture that cannot be kept up with is asked for as another VARIANT, and its size is left alone", async (t) => {
190
+ const { manager, session, dirPath } = await managerWithSession();
191
+ t.after(async () => {
192
+ await manager.lifecycle.disposeAll();
193
+ // The store closes its watch on the directory as it drops the output, and
194
+ // on Windows the directory stays held until the event loop has turned.
195
+ await new Promise((resolve) => setImmediate(resolve));
196
+ await rm(dirPath, { recursive: true, force: true });
197
+ });
198
+
199
+ const sizeBefore = `${session.encodeWidth}x${session.encodeHeight}`;
200
+ // Below realtime over its own working time, and the viewer's buffer runs
201
+ // dry on its trend although their link carries the stream.
202
+ measureSpeed([...session.runs][0], 0.7);
203
+ drainingReports(manager.viewers.get("viewer"), 80);
204
+
205
+ await manager.quality.noteViewerReported(session.id, "viewer");
206
+
207
+ assert.equal(
208
+ `${session.encodeWidth}x${session.encodeHeight}`,
209
+ sizeBefore,
210
+ "the size the init segment describes must survive the step — that is the whole fault"
211
+ );
212
+ assert.ok(manager.viewers.get("viewer").qualityAsk, "the step is a request to the AUTO viewer to move variant");
213
+ assert.ok(
214
+ manager.viewers.get("viewer").qualityAsk.height < 720,
215
+ `a step DOWN, and 720p was on screen (asked for ${manager.viewers.get("viewer").qualityAsk?.height}p)`
216
+ );
217
+ });
218
+
219
+ test("a manual viewer is never sent an automatic quality request", async (t) => {
220
+ const { manager, session, dirPath } = await managerWithSession();
221
+ t.after(async () => {
222
+ await manager.lifecycle.disposeAll();
223
+ // The store closes its watch on the directory as it drops the output, and
224
+ // on Windows the directory stays held until the event loop has turned.
225
+ await new Promise((resolve) => setImmediate(resolve));
226
+ await rm(dirPath, { recursive: true, force: true });
227
+ });
228
+ manager.viewers.get("viewer").qualityMode = "manual";
229
+ measureSpeed([...session.runs][0], 0.7);
230
+ drainingReports(manager.viewers.get("viewer"), 80);
231
+
232
+ await manager.quality.noteViewerReported(session.id, "viewer");
233
+
234
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null);
235
+ const progress = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
236
+ assert.equal(progress.requestedHeight, 0);
237
+ });
238
+
239
+ test("the request reaches the browser in the progress report, and stops once the viewer is there", async (t) => {
240
+ const { manager, session, dirPath } = await managerWithSession();
241
+ t.after(async () => {
242
+ await manager.lifecycle.disposeAll();
243
+ // The store closes its watch on the directory as it drops the output, and
244
+ // on Windows the directory stays held until the event loop has turned.
245
+ await new Promise((resolve) => setImmediate(resolve));
246
+ await rm(dirPath, { recursive: true, force: true });
247
+ });
248
+
249
+ manager.viewers.get("viewer").qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
250
+ const asked = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
251
+ assert.equal(asked.requestedHeight, 480, "the request travels with every progress report");
252
+
253
+ // The player moved: the variant it is now watching IS the height asked for.
254
+ session.variantHeight = 480;
255
+ const answered = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
256
+ assert.equal(answered.requestedHeight, 0, "a request the viewer has answered is not repeated");
257
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "and it is let go of, not merely hidden");
258
+ });
259
+
260
+ test("a request stands while its conditions hold, and the next report that does not ask for it lets it go", async (t) => {
261
+ const { manager, session, dirPath } = await managerWithSession();
262
+ t.after(async () => {
263
+ await manager.lifecycle.disposeAll();
264
+ // The store closes its watch on the directory as it drops the output, and
265
+ // on Windows the directory stays held until the event loop has turned.
266
+ await new Promise((resolve) => setImmediate(resolve));
267
+ await rm(dirPath, { recursive: true, force: true });
268
+ });
269
+
270
+ // Asked when their buffer was running dry; no chosen time ends it.
271
+ manager.viewers.get("viewer").qualityAsk = { height: 480, at: Date.now() - 120_000, reason: "measured" };
272
+ const standing = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
273
+ assert.equal(standing.requestedHeight, 480, "two minutes on, it still stands: nothing has said otherwise");
274
+
275
+ // Their next report shows a buffer that grows: what it was asked for is gone.
276
+ // The machine has no room to spare, so nothing else is asked in its place.
277
+ measureSpeed([...session.runs][0], 0.9);
278
+ fillingReports(manager.viewers.get("viewer"), null);
279
+ await manager.quality.noteViewerReported(session.id, "viewer");
280
+
281
+ const progress = await manager.viewerRequests.getSessionProgress(BASE_ID, "viewer");
282
+ assert.equal(progress.requestedHeight, 0);
283
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "let go by the judgement that did not repeat it");
284
+ });
285
+
286
+ test("a request the next report asks for again stands", async (t) => {
287
+ const { manager, session, dirPath } = await managerWithSession();
288
+ t.after(async () => {
289
+ await manager.lifecycle.disposeAll();
290
+ await new Promise((resolve) => setImmediate(resolve));
291
+ await rm(dirPath, { recursive: true, force: true });
292
+ });
293
+ measureSpeed([...session.runs][0], 0.7);
294
+ drainingReports(manager.viewers.get("viewer"), 80);
295
+ await manager.quality.noteViewerReported(session.id, "viewer");
296
+ const asked = manager.viewers.get("viewer").qualityAsk;
297
+ assert.ok(asked, "the machine cannot keep up and the buffer runs dry");
298
+
299
+ drainingReports(manager.viewers.get("viewer"), 80);
300
+ await manager.quality.noteViewerReported(session.id, "viewer");
301
+
302
+ assert.equal(manager.viewers.get("viewer").qualityAsk, asked, "the same request, not let go and not made again");
303
+ });
304
+
305
+ test("a COPIED picture is never asked to slow its encoder, because it has none", async (t) => {
306
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
307
+ t.after(async () => {
308
+ await manager.lifecycle.disposeAll();
309
+ // The store closes its watch on the directory as it drops the output, and
310
+ // on Windows the directory stays held until the event loop has turned.
311
+ await new Promise((resolve) => setImmediate(resolve));
312
+ await rm(dirPath, { recursive: true, force: true });
313
+ });
314
+
315
+ // Whatever this reading says, a copy has no encoder to make cheaper: moving
316
+ // the viewer to a RE-ENCODED rung costs the machine more, not less.
317
+ measureSpeed([...session.runs][0], 0.4);
318
+ drainingReports(manager.viewers.get("viewer"), 80);
319
+
320
+ await manager.quality.noteViewerReported(session.id, "viewer");
321
+
322
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "the copy path's lever is the viewer's link, not the CPU");
323
+ });
324
+
325
+ test("the output's own rate control is what reaches ffmpeg, and nothing about the size moves with it", () => {
326
+ // Two limits are two outputs (roadmap item 97, step 10): the figures are
327
+ // read off the output's identity and handed to the encoder as they are. The
328
+ // level is the nominal output's, so every limit at one size declares the
329
+ // same one.
330
+ const nominal = softwareRateControlFor({ width: 1280, height: 720, fps: 24 });
331
+ const lower = softwareRateControlFor({ width: 1280, height: 720, fps: 24, capKbps: 1200 });
332
+ const build = (rateControl) => softwareDescriptor().buildVideoArgs({
333
+ targetWidth: 1280,
334
+ targetHeight: 720,
335
+ segmentDurationSec: 4,
336
+ fps: 24,
337
+ rateControl
338
+ });
339
+ const atNominal = build(nominal);
340
+ const atLower = build(lower);
341
+
342
+ assert.equal(atNominal[atNominal.indexOf("-maxrate") + 1], `${maxrateKbpsFor(nominalKbpsFor({ width: 1280, height: 720 }))}k`);
343
+ assert.equal(atLower[atLower.indexOf("-maxrate") + 1], `${maxrateKbpsFor(1200)}k`);
344
+ assert.equal(lower.level, nominal.level, "a lower limit is declared at the nominal output's level");
345
+ assert.equal(atLower[atLower.indexOf("-level:v") + 1], nominal.level);
346
+ assert.deepEqual(
347
+ atNominal.slice(0, atNominal.indexOf("-maxrate")),
348
+ atLower.slice(0, atLower.indexOf("-maxrate")),
349
+ "the scale filter, the codec and the preset are untouched by the limit"
350
+ );
351
+ assert.equal(build(null).includes("-maxrate"), false, "an output that states no limit is given none");
352
+ assert.throws(
353
+ () => softwareRateControlFor({ width: 1280, height: 720, fps: 24, capKbps: nominalKbpsFor({ width: 1280, height: 720 }) + 1 }),
354
+ RangeError,
355
+ "a limit above the size's own is refused, not lowered"
356
+ );
357
+ });
358
+
359
+ test("the size an init segment describes is read from the init, not assumed", () => {
360
+ // A minimal moov/trak/mdia/minf/stbl/stsd with one avc1 entry. Built here
361
+ // rather than taken from a fixture so the offsets under test are the ones
362
+ // ISO/IEC 14496-12 states, and a fixture cannot quietly encode a mistake.
363
+ const avc1 = Buffer.alloc(8 + 8 + 16 + 4);
364
+ avc1.writeUInt32BE(avc1.length, 0);
365
+ avc1.write("avc1", 4, "latin1");
366
+ avc1.writeUInt16BE(960, 32);
367
+ avc1.writeUInt16BE(540, 34);
368
+
369
+ const stsd = Buffer.concat([Buffer.alloc(8 + 8), avc1]);
370
+ stsd.writeUInt32BE(stsd.length, 0);
371
+ stsd.write("stsd", 4, "latin1");
372
+ stsd.writeUInt32BE(1, 12); // entry_count
373
+
374
+ const wrap = (type, payload) => {
375
+ const box = Buffer.alloc(8 + payload.length);
376
+ box.writeUInt32BE(box.length, 0);
377
+ box.write(type, 4, "latin1");
378
+ payload.copy(box, 8);
379
+ return box;
380
+ };
381
+ const init = wrap("moov", wrap("trak", wrap("mdia", wrap("minf", wrap("stbl", stsd)))));
382
+
383
+ assert.deepEqual(readVideoSampleSize(init), { width: 960, height: 540 });
384
+ assert.equal(readVideoSampleSize(Buffer.alloc(0)), null);
385
+ });
386
+
387
+ test("a COPIED picture too thick for the viewer's link is asked for as a smaller VARIANT", async (t) => {
388
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
389
+ t.after(async () => {
390
+ await manager.lifecycle.disposeAll();
391
+ // The store closes its watch on the directory as it drops the output, and
392
+ // on Windows the directory stays held until the event loop has turned.
393
+ await new Promise((resolve) => setImmediate(resolve));
394
+ await rm(dirPath, { recursive: true, force: true });
395
+ });
396
+
397
+ // Four seconds of segment at 2 MB is ~4 Mbit/s of stream. The viewer reports
398
+ // a link that cannot carry it and a buffer that is running dry.
399
+ await produceSegments(session, 2_000_000);
400
+ drainingReports(manager.viewers.of(session, "viewer"), 1.0);
401
+
402
+ await manager.quality.noteViewerReported(session.id, "viewer");
403
+
404
+ assert.ok(
405
+ manager.viewers.get("viewer").qualityAsk,
406
+ "a copy has no encoder to bound, so the only way to send fewer bits is another rendering of the film"
407
+ );
408
+ assert.equal(manager.viewers.get("viewer").qualityAsk.urgent, true, "their buffer runs dry first: no cushion is waited for");
409
+ assert.ok(manager.viewers.get("viewer").qualityAsk.height < 1080, `a step down (asked for ${manager.viewers.get("viewer").qualityAsk?.height}p)`);
410
+ });
411
+
412
+ test("with two viewers each link decides for its own viewer, not the worst for both", async (t) => {
413
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
414
+ t.after(async () => {
415
+ await manager.lifecycle.disposeAll();
416
+ // The store closes its watch on the directory as it drops the output, and
417
+ // on Windows the directory stays held until the event loop has turned.
418
+ await new Promise((resolve) => setImmediate(resolve));
419
+ await rm(dirPath, { recursive: true, force: true });
420
+ });
421
+
422
+ await produceSegments(session, 2_000_000);
423
+ // One viewer is comfortable and reported LAST, which under a single field was
424
+ // the whole of what the budget saw. The other cannot carry the stream and is
425
+ // running dry.
426
+ manager.viewers.of(session, "thin").qualityMode = "auto";
427
+ drainingReports(manager.viewers.of(session, "thin"), 1.0);
428
+ manager.viewers.of(session, "fat").qualityMode = "auto";
429
+ fillingReports(manager.viewers.of(session, "fat"), 80);
430
+
431
+ await manager.quality.noteViewerReported(session.id, "thin");
432
+ await manager.quality.noteViewerReported(session.id, "fat");
433
+
434
+ assert.ok(
435
+ manager.viewers.get("thin").qualityAsk,
436
+ "the viewer who cannot keep up is asked, whichever of them reported most recently"
437
+ );
438
+ assert.equal(
439
+ manager.viewers.get("fat").qualityAsk,
440
+ null,
441
+ "and ONLY them: a thin link is its owner's, and the viewer beside them keeps their picture"
442
+ );
443
+ });
444
+
445
+ test("a reading stops counting when the person leaves, not when it gets old", async (t) => {
446
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
447
+ t.after(async () => {
448
+ await manager.lifecycle.disposeAll();
449
+ // The store closes its watch on the directory as it drops the output, and
450
+ // on Windows the directory stays held until the event loop has turned.
451
+ await new Promise((resolve) => setImmediate(resolve));
452
+ await rm(dirPath, { recursive: true, force: true });
453
+ });
454
+
455
+ await produceSegments(session, 2_000_000);
456
+ // A LINK READING DOES NOT EXPIRE. It is the last thing known about that link,
457
+ // and how fast a link is does not change because nobody measured it for a
458
+ // minute — the page keeps its own last figure for the same reason. What ends
459
+ // a reading is the person leaving, which is presence, and presence is the
460
+ // connection: silence removes nobody (2026-09-05, a soundtrack's encoder
461
+ // stopped because those two questions had one answer).
462
+ const gone = manager.viewers.of(session, "gone");
463
+ gone.qualityMode = "auto";
464
+ gone.report({ linkMbps: 1.0, bufferedAheadSec: 1.5, positionSeconds: 40, playing: true }, Date.now() - 120_000);
465
+ gone.gone = true;
466
+ recordViewerReport({
467
+ outputs: manager.outputs,
468
+ viewers: manager.viewers,
469
+ sessionId: session.id,
470
+ report: { linkMbps: 80, bufferedAheadSec: 60, consumerId: "here", positionSeconds: 40 }
471
+ });
472
+ manager.viewers.get("here").qualityMode = "auto";
473
+
474
+ await manager.quality.noteViewerReported(session.id, "here");
475
+
476
+ assert.equal(manager.viewers.forOutput(session).size, 3, "the viewer is still known — silence is not leaving");
477
+ // Their reading is not deleted anywhere: it is simply not theirs to give any
478
+ // more, because they are not here. Nothing walks it for a decision.
479
+ assert.equal(
480
+ manager.viewers.get("gone").linkReading()?.linkMbps,
481
+ 1.0,
482
+ "their last reading stands as the last thing known about that link"
483
+ );
484
+ assert.equal(manager.viewers.get("here").qualityAsk, null, "the viewer who is here can carry the picture");
485
+ });
486
+
487
+ test("the way BACK UP exists, one rung at a time", async (t) => {
488
+ const { manager, session, dirPath } = await managerWithSession();
489
+ t.after(async () => {
490
+ await manager.lifecycle.disposeAll();
491
+ // The store closes its watch on the directory as it drops the output, and
492
+ // on Windows the directory stays held until the event loop has turned.
493
+ await new Promise((resolve) => setImmediate(resolve));
494
+ await rm(dirPath, { recursive: true, force: true });
495
+ });
496
+
497
+ // The viewer is on 480p, the machine makes it ahead of realtime over its own
498
+ // working time, and their buffer grows and holds more than another output
499
+ // takes to be ready. No window has to pass: every term is measured.
500
+ session.variantHeight = 480;
501
+ session.encodeWidth = 854;
502
+ session.encodeHeight = 480;
503
+ measureSpeed([...session.runs][0], 2.4);
504
+ // What another output takes to be ready here: the picture's first segment
505
+ // on the addon host, field 2026-08-31.
506
+ manager.hostTimings.rememberFirstSegmentLatency(8_400);
507
+ // Their link is not measured here: what is under test is the room, and a
508
+ // measured link would also weigh a soundtrack this fixture states no rate for.
509
+ fillingReports(manager.viewers.get("viewer"), null);
510
+
511
+ await manager.quality.noteViewerReported(session.id, "viewer");
512
+
513
+ assert.ok(manager.viewers.get("viewer").qualityAsk, "for most of this project's life there was no step up at all");
514
+ assert.equal(
515
+ manager.viewers.get("viewer").qualityAsk.height,
516
+ 540,
517
+ "one rung at a time: the lowest height above the one on screen, never above the source"
518
+ );
519
+ });
520
+
521
+ test("a re-encoded picture too thick for the viewer's link is asked for as a smaller VARIANT, and its output is left as it is", async (t) => {
522
+ // The limit on a picture's bitrate is part of the output now, so a thin link
523
+ // no longer lowers the limit of the output every viewer of it is watching.
524
+ // Until each viewer is served an output of their own (roadmap item 97, steps
525
+ // 11-12), the one lever is a lower height, asked of a viewer in AUTO.
526
+ const { manager, session, dirPath } = await managerWithSession();
527
+ t.after(async () => {
528
+ await manager.lifecycle.disposeAll();
529
+ // The store closes its watch on the directory as it drops the output, and
530
+ // on Windows the directory stays held until the event loop has turned.
531
+ await new Promise((resolve) => setImmediate(resolve));
532
+ await rm(dirPath, { recursive: true, force: true });
533
+ });
534
+ const keyBefore = session.outputKey;
535
+
536
+ await produceSegments(session, 2_000_000);
537
+ manager.viewers.of(session, "viewer").qualityMode = "auto";
538
+ drainingReports(manager.viewers.of(session, "viewer"), 1.0);
539
+
540
+ await manager.quality.noteViewerReported(session.id, "viewer");
541
+
542
+ assert.ok(manager.viewers.get("viewer").qualityAsk, "the viewer is asked to move to a smaller variant");
543
+ assert.equal(session.outputKey, keyBefore, "and the output they were on is not altered under anybody");
544
+ });
545
+
546
+ test("a stream that publishes no variants is left alone, and said so once", async (t) => {
547
+ const { manager, session, dirPath } = await managerWithSession({
548
+ transcodeVideo: false,
549
+ // A copy whose keyframe index could not be read falls back to an even grid
550
+ // ffmpeg does not cut on. Nothing can be aligned to that, so there is no
551
+ // master and no variant to move to.
552
+ cutGrid: "even"
553
+ });
554
+ t.after(async () => {
555
+ await manager.lifecycle.disposeAll();
556
+ // The store closes its watch on the directory as it drops the output, and
557
+ // on Windows the directory stays held until the event loop has turned.
558
+ await new Promise((resolve) => setImmediate(resolve));
559
+ await rm(dirPath, { recursive: true, force: true });
560
+ });
561
+
562
+ await produceSegments(session, 2_000_000);
563
+ drainingReports(manager.viewers.of(session, "viewer"), 1.0);
564
+
565
+ await manager.quality.noteViewerReported(session.id, "viewer");
566
+
567
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "asking a player with no variants to change variant is nothing");
568
+ assert.equal(qualityStateOf(session).saidNoVariants, true, "and the reason is stated once, not once per window");
569
+ });
570
+
571
+ test("a height this machine has been MEASURED failing at is not what the way back up offers", async (t) => {
572
+ const { manager, session, dirPath } = await managerWithSession({
573
+ softwarePresetBenchmark: [{ preset: "ultrafast", pixelsPerSec: 1e6 }]
574
+ });
575
+ t.after(async () => {
576
+ await manager.lifecycle.disposeAll();
577
+ // The store closes its watch on the directory as it drops the output, and
578
+ // on Windows the directory stays held until the event loop has turned.
579
+ await new Promise((resolve) => setImmediate(resolve));
580
+ await rm(dirPath, { recursive: true, force: true });
581
+ });
582
+
583
+ // The base ran 720p at half realtime and the viewer was stepped down to 480p.
584
+ // The base's own height used to be exempt from every refusal — it was the
585
+ // rung on screen, back when a step changed the encode inside it — so the way
586
+ // back up would have asked for 720p again, failed again, and stepped down
587
+ // again, about every hundred seconds for the length of the film.
588
+ qualityStateOf(session).lastAloneSpeed = 0.5;
589
+ session.variantHeight = 720;
590
+
591
+ const offered = manager.quality.offeredHeights(session);
592
+
593
+ assert.ok(!offered.includes(720) || manager.outputs.variantHeightOf(session) === 720);
594
+ // Now on the 480p variant: 720p has a reading of its own and must be gone.
595
+ session.variantHeight = 480;
596
+ session.encodeHeight = 480;
597
+ session.encodeWidth = 854;
598
+ assert.ok(
599
+ !manager.quality.offeredHeights(session).includes(720),
600
+ "a rung measured below realtime is withdrawn once the viewer has left it"
601
+ );
602
+ });
603
+
604
+ test("a request is answered when the viewers watching are on that height, whoever they are", async (t) => {
605
+ const { manager, session, dirPath } = await managerWithSession();
606
+ t.after(async () => {
607
+ await manager.lifecycle.disposeAll();
608
+ // The store closes its watch on the directory as it drops the output, and
609
+ // on Windows the directory stays held until the event loop has turned.
610
+ await new Promise((resolve) => setImmediate(resolve));
611
+ await rm(dirPath, { recursive: true, force: true });
612
+ });
613
+ // A named viewer followed the request to a 480p step. The step is an output
614
+ // of its own; the picture's own height is still 720.
615
+ const stepId = "aaaaaaaabbbbdddd";
616
+ const step = { ...fakeSession({ dirPath }), id: stepId, isStep: true, variantHeight: 480 };
617
+ step.outputKey = `${session.outputKey}:step480`;
618
+ manager.outputs.set(stepId, step);
619
+ manager.outputs.markStep(step);
620
+ manager.viewers.of(session, "alice").qualityMode = "auto";
621
+ manager.viewers.of(session, "alice").activeVariantId = stepId;
622
+
623
+ manager.viewers.get("alice").qualityAsk = { height: 480, at: Date.now(), reason: "measured" };
624
+ const answered = await manager.viewerRequests.getSessionProgress(BASE_ID, "alice");
625
+
626
+ assert.equal(answered.requestedHeight, 0, "the viewer is on the height asked for");
627
+ assert.equal(manager.viewers.get("alice").qualityAsk, null, "so the request is let go of");
628
+ });
629
+
630
+ test("a thin link whose buffer is filling moves nothing: the trend, not the reading, decides", async (t) => {
631
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
632
+ t.after(async () => {
633
+ await manager.lifecycle.disposeAll();
634
+ // The store closes its watch on the directory as it drops the output, and
635
+ // on Windows the directory stays held until the event loop has turned.
636
+ await new Promise((resolve) => setImmediate(resolve));
637
+ await rm(dirPath, { recursive: true, force: true });
638
+ });
639
+ await produceSegments(session, 2_000_000);
640
+ fillingReports(manager.viewers.of(session, "viewer"), 1.0);
641
+
642
+ await manager.quality.noteViewerReported(session.id, "viewer");
643
+
644
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null);
645
+ });
646
+
647
+ test("a step up being prepared is dropped once the viewer's buffer starts running dry", async (t) => {
648
+ const { manager, session, dirPath } = await managerWithSession();
649
+ t.after(async () => {
650
+ await manager.lifecycle.disposeAll();
651
+ // The store closes its watch on the directory as it drops the output, and
652
+ // on Windows the directory stays held until the event loop has turned.
653
+ await new Promise((resolve) => setImmediate(resolve));
654
+ await rm(dirPath, { recursive: true, force: true });
655
+ });
656
+ session.variantHeight = 480;
657
+ await produceSegments(session, 200_000);
658
+ const viewer = manager.viewers.get("viewer");
659
+ viewer.askQuality(540, "room to spare", Date.now());
660
+ drainingReports(viewer, 80);
661
+
662
+ await manager.quality.noteViewerReported(session.id, "viewer");
663
+
664
+ assert.equal(viewer.qualityAsk, null, "the conditions it was asked under have gone back");
665
+ });
666
+
667
+ test("a picture seen larger than the rung on screen is asked one rung up, when there is room", async (t) => {
668
+ const { manager, session, dirPath } = await managerWithSession();
669
+ t.after(async () => {
670
+ await manager.lifecycle.disposeAll();
671
+ // The store closes its watch on the directory as it drops the output, and
672
+ // on Windows the directory stays held until the event loop has turned.
673
+ await new Promise((resolve) => setImmediate(resolve));
674
+ await rm(dirPath, { recursive: true, force: true });
675
+ });
676
+ session.variantHeight = 480;
677
+ session.encodeWidth = 854;
678
+ session.encodeHeight = 480;
679
+ measureSpeed([...session.runs][0], 2.4);
680
+ // What another output takes to be ready here: the picture's first segment
681
+ // on the addon host, field 2026-08-31.
682
+ manager.hostTimings.rememberFirstSegmentLatency(8_400);
683
+ manager.viewers.get("viewer").noteVisiblePicture({ width: 1920, height: 1080 });
684
+ fillingReports(manager.viewers.get("viewer"), null);
685
+
686
+ await manager.quality.noteViewerReported(session.id, "viewer");
687
+
688
+ assert.equal(manager.viewers.get("viewer").qualityAsk?.height, 540);
689
+ assert.equal(manager.viewers.get("viewer").qualityAsk?.urgent, false, "a step up waits for the cushion");
690
+ });
691
+
692
+ test("a picture seen smaller than the rung on screen moves nothing until a rung of its height is ready", async (t) => {
693
+ const { manager, session, dirPath } = await managerWithSession();
694
+ t.after(async () => {
695
+ await manager.lifecycle.disposeAll();
696
+ // The store closes its watch on the directory as it drops the output, and
697
+ // on Windows the directory stays held until the event loop has turned.
698
+ await new Promise((resolve) => setImmediate(resolve));
699
+ await rm(dirPath, { recursive: true, force: true });
700
+ });
701
+ manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
702
+
703
+ await manager.quality.noteViewerReported(session.id, "viewer");
704
+
705
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "no 360p rung is made yet; nothing is started for this alone");
706
+ });
707
+
708
+ test("a COPY taller than the picture seen is left alone", async (t) => {
709
+ const { manager, session, dirPath } = await managerWithSession({ transcodeVideo: false });
710
+ t.after(async () => {
711
+ await manager.lifecycle.disposeAll();
712
+ // The store closes its watch on the directory as it drops the output, and
713
+ // on Windows the directory stays held until the event loop has turned.
714
+ await new Promise((resolve) => setImmediate(resolve));
715
+ await rm(dirPath, { recursive: true, force: true });
716
+ });
717
+ manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
718
+ // Every smaller rung is ready for them: what stops the move is the rule
719
+ // about copies, and nothing else.
720
+ manager.renditions.heightReadyFor = () => true;
721
+
722
+ await manager.quality.noteViewerReported(session.id, "viewer");
723
+
724
+ assert.equal(manager.viewers.get("viewer").qualityAsk, null, "a copy is never re-encoded for being taller than the screen");
725
+ });
726
+
727
+ test("a step down for the machine goes to the rung the picture seen bounds, where that is lower", async (t) => {
728
+ const { manager, session, dirPath } = await managerWithSession();
729
+ t.after(async () => {
730
+ await manager.lifecycle.disposeAll();
731
+ // The store closes its watch on the directory as it drops the output, and
732
+ // on Windows the directory stays held until the event loop has turned.
733
+ await new Promise((resolve) => setImmediate(resolve));
734
+ await rm(dirPath, { recursive: true, force: true });
735
+ });
736
+ manager.viewers.get("viewer").noteVisiblePicture({ width: 640, height: 360 });
737
+ measureSpeed([...session.runs][0], 0.7);
738
+ drainingReports(manager.viewers.get("viewer"), 80);
739
+
740
+ await manager.quality.noteViewerReported(session.id, "viewer");
741
+
742
+ const asked = manager.viewers.get("viewer").qualityAsk?.height;
743
+ assert.ok(asked, "the machine cannot keep up: a step down is asked");
744
+ assert.ok(asked <= 360, `not a rung between that the screen cannot show (asked for ${asked}p)`);
745
+ });
746
+
747
+ test("a machine below realtime whose viewer's buffer is filling moves nothing", async (t) => {
748
+ const { manager, session, dirPath } = await managerWithSession();
749
+ t.after(async () => {
750
+ await manager.lifecycle.disposeAll();
751
+ await new Promise((resolve) => setImmediate(resolve));
752
+ await rm(dirPath, { recursive: true, force: true });
753
+ });
754
+ // What the cushion already holds covers the shortfall: no chosen window of
755
+ // slowness decides, the viewer's own buffer trend does.
756
+ measureSpeed([...session.runs][0], 0.7);
757
+ fillingReports(manager.viewers.get("viewer"), 80);
758
+
759
+ await manager.quality.noteViewerReported(session.id, "viewer");
760
+
761
+ assert.ok(!(manager.viewers.get("viewer").qualityAsk?.height < 720), "no step down while the buffer grows");
762
+ });