@torrent-tv/proxy 2.81.2 → 2.83.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.
@@ -1,1843 +1,1854 @@
1
- /**
2
- * @file Hardware-accelerated H.264 encoder auto-detection.
3
- *
4
- * Probes the ffmpeg build and the host for a usable hardware H.264 encoder
5
- * (NVENC / QSV / VAAPI / V4L2 M2M), verifying each candidate with a real
6
- * test-encode before selecting it. Falls back to software libx264 when no
7
- * hardware encoder is present or working.
8
- *
9
- * Deployment-agnostic: relies only on ffmpeg, the filesystem and
10
- * `process.platform`; makes no assumptions about Home Assistant or any
11
- * specific host. A garbled or unsupported hardware path simply fails its
12
- * test-encode and is skipped, so the worst case is software encoding.
13
- *
14
- * A descriptor exposes:
15
- * - `name` human-readable encoder id (e.g. "h264_vaapi")
16
- * - `kind` "software" | "vaapi" | "qsv" | "nvenc" | "v4l2m2m"
17
- * - `device` device node path or null
18
- * - `inputArgs` ffmpeg args inserted before `-i` (decode/hwaccel setup)
19
- * - `buildVideoArgs({ targetWidth, targetHeight, segmentDurationSec })`
20
- * ffmpeg video filter + encoder args inserted after `-map`s
21
- */
22
-
23
- import { spawn } from "node:child_process";
24
- import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
25
- import { mkdtemp, readFile, rm } from "node:fs/promises";
26
- import os from "node:os";
27
- import path from "node:path";
28
- import { fitDecodeCost } from "./decode-cost-fit.js";
29
- import { penaltiesFrom } from "./encode/contention.js";
30
- import { fileURLToPath } from "node:url";
31
- import {
32
- parseFfmpegBitrateKbps,
33
- parseFfmpegDurationSeconds,
34
- parseFfmpegVideoDimensions,
35
- parseFfmpegVideoFps
36
- } from "./ffmpeg-banner.js";
37
-
38
- import { keyFrameArgs, SOFTWARE_CRF, TRANSCODE_FPS } from "./encode/args.js";
39
- // The five kinds, one class each. Detection and benchmarking stay in this file;
40
- // how a kind is driven belongs to the kind.
41
- import {
42
- NvencEncoder,
43
- QsvEncoder,
44
- SoftwareEncoder,
45
- V4l2m2mEncoder,
46
- VaapiEncoder
47
- } from "./encode/index.js";
48
- // Re-exported so every caller goes on importing these figures from here:
49
- // the same calculation, moved to sit beside the encoder kinds built from it.
50
- export {
51
- chooseOutputFps,
52
- maxrateKbpsFor,
53
- nominalKbpsForHeight,
54
- nominalKbpsForMaxrate,
55
- TRANSCODE_FPS
56
- } from "./encode/args.js";
57
-
58
- // libx264 presets to benchmark, ordered slowest/highest-quality → fastest.
59
- const BENCHMARK_PRESETS = ["fast", "faster", "veryfast", "superfast", "ultrafast"];
60
- const BENCHMARK_REF_W = 640;
61
- const BENCHMARK_REF_H = 360;
62
- const BENCHMARK_DURATION_SEC = 3;
63
- /**
64
- * The narrowest window a slope may be taken over. Measured 2026-08-15: at a
65
- * fifth of a second the readings were noisy enough to put `faster` and
66
- * `veryfast` BELOW `fast`, which libx264 cannot do and `pickSoftwarePreset`
67
- * walks the list assuming it ascends. Half a second was still noisy enough for that
68
- * (measured again: veryfast below faster, twice), so a full second it is —
69
- * about six seconds of startup for a ladder the whole budget then rests on.
70
- */
71
- const ENCODE_BENCHMARK_WINDOW_SEC = 1;
72
- /** The narrowest window that may be used when a run ends early. */
73
- const ENCODE_BENCHMARK_MIN_WINDOW_SEC = 0.2;
74
- /** Above this a reading is a fault, not a fast machine. */
75
- const ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED = 1000;
76
- /**
77
- * A preset that has not reported twice in this long is hung, not slow: reports
78
- * arrive twice a second whatever the encoding speed.
79
- */
80
- const ENCODE_BENCHMARK_TIMEOUT_MS = 10_000;
81
- /**
82
- * How many times the calibration clip is joined to itself to measure copying.
83
- *
84
- * Not a figure about the machine: it is how much film the reading needs to have
85
- * in front of it. A copy runs at hundreds of times realtime, and the slope is
86
- * taken over a window of one second, so the input has to hold more film than the
87
- * fastest plausible host gets through in that second. Forty laps of a five-second
88
- * clip is 200 s of film, which covers the ceiling `slopeOf` will accept.
89
- */
90
- /** Progress reports arrive line by line. */
91
- const NEWLINE = String.fromCharCode(10);
92
- // Producing one second of video per second of clock. Not a margin and not a
93
- // choice the definition of keeping up, and the bar when nothing better is
94
- // known about the supply this step will meet.
95
- const REALTIME = 1;
96
- // The bar where decoding CANNOT be priced no calibration fit, or a source the
97
- // probe said too little about. This one is not measured and cannot be: the
98
- // prediction it guards counts encoding only, which on the field host was
99
- // several times optimistic, and there is no reading on such a host to correct
100
- // it with. It is left at the figure it has had since before decoding was
101
- // priced, because lowering it to realtime would make the least-measured hosts
102
- // the most permissive. Where decoding IS priced, nothing chosen remains.
103
- const UNPRICED_DECODE_BAR = 1.8;
104
-
105
-
106
- // The five kinds live in `encode/`, one class each, and these keep the names
107
- // every caller already uses. A kind states its own arguments and its own
108
- // ladder of speed settings; detection and benchmarking stay here.
109
- /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
110
- export function softwareDescriptor() {
111
- return new SoftwareEncoder();
112
- }
113
-
114
- /**
115
- * @param {string} device
116
- * @returns {import("./hwaccel.js").VideoEncoderDescriptor}
117
- */
118
- function vaapiDescriptor(device) {
119
- return new VaapiEncoder(device);
120
- }
121
-
122
- /**
123
- * @param {string} device
124
- * @returns {import("./hwaccel.js").VideoEncoderDescriptor}
125
- */
126
- function qsvDescriptor(device) {
127
- return new QsvEncoder(device);
128
- }
129
-
130
- /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
131
- function nvencDescriptor() {
132
- return new NvencEncoder();
133
- }
134
-
135
- /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
136
- function v4l2m2mDescriptor() {
137
- return new V4l2m2mEncoder();
138
- }
139
-
140
-
141
-
142
- /**
143
- * @typedef {Object} VideoEncoderDescriptor
144
- * @property {string} name
145
- * @property {"software"|"vaapi"|"qsv"|"nvenc"|"v4l2m2m"} kind
146
- * @property {string|null} device
147
- * @property {string[]} inputArgs
148
- * @property {(opts: { targetWidth: number, targetHeight: number, segmentDurationSec: number, preset?: string, fps?: number, tonemap?: boolean, forcedKeyframeTimes?: number[] | null, nominalKbps?: number | null }) => string[]} buildVideoArgs
149
- */
150
-
151
- /**
152
- * Run ffmpeg and resolve with its exit code and captured output.
153
- *
154
- * @param {string} ffmpegBin
155
- * @param {string[]} args
156
- * @param {number} [timeoutMs=12000]
157
- * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
158
- */
159
- function runFfmpeg(ffmpegBin, args, timeoutMs = 12000) {
160
- return new Promise((resolve) => {
161
- let stdout = "";
162
- let stderr = "";
163
- let settled = false;
164
- let child;
165
- const finish = (code) => {
166
- if (settled) {
167
- return;
168
- }
169
- settled = true;
170
- resolve({ code, stdout, stderr });
171
- };
172
- try {
173
- child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
174
- } catch {
175
- finish(-1);
176
- return;
177
- }
178
- const timer = setTimeout(() => {
179
- try {
180
- child.kill("SIGKILL");
181
- } catch {
182
- // already gone
183
- }
184
- finish(-1);
185
- }, timeoutMs);
186
- child.stdout.on("data", (chunk) => {
187
- stdout += String(chunk);
188
- });
189
- child.stderr.on("data", (d) => {
190
- stderr += String(d);
191
- });
192
- child.on("error", () => {
193
- clearTimeout(timer);
194
- finish(-1);
195
- });
196
- child.on("exit", (code) => {
197
- clearTimeout(timer);
198
- finish(code ?? -1);
199
- });
200
- });
201
- }
202
-
203
- /** @returns {string[]} /dev/dri/renderD* nodes (VAAPI/QSV). */
204
- function listRenderNodes() {
205
- try {
206
- return readdirSync("/dev/dri")
207
- .filter((n) => n.startsWith("renderD"))
208
- .map((n) => `/dev/dri/${n}`)
209
- .sort();
210
- } catch {
211
- return [];
212
- }
213
- }
214
-
215
- /** @returns {boolean} Whether any /dev/nvidia* node exists (NVENC). */
216
- function hasNvidiaDevice() {
217
- try {
218
- return readdirSync("/dev").some((n) => /^nvidia(\d+)?$/.test(n));
219
- } catch {
220
- return false;
221
- }
222
- }
223
-
224
- /** @returns {boolean} Whether any /dev/video* node exists (V4L2 M2M). */
225
- function hasV4l2Device() {
226
- try {
227
- return readdirSync("/dev").some((n) => /^video\d+$/.test(n));
228
- } catch {
229
- return false;
230
- }
231
- }
232
-
233
- /**
234
- * Build a full ffmpeg command that encodes a short, *moving* synthetic clip
235
- * (testsrc2 far more representative than a static black frame) through the
236
- * candidate encoder into real HLS segments in `outDir`, with keyframes forced
237
- * on segment boundaries. Verifying the resulting segments (see
238
- * {@link verifySegmentsDecodeCleanly}) catches encoders that silently produce
239
- * a corrupted or non-IDR-aligned stream (e.g. some V4L2 M2M builds).
240
- *
241
- * @param {VideoEncoderDescriptor} descriptor
242
- * @param {number} segmentDurationSec
243
- * @param {string} outDir
244
- * @returns {string[]}
245
- */
246
- function buildEncoderTestArgs(descriptor, segmentDurationSec, outDir) {
247
- const durationSec = Math.max(8, segmentDurationSec * 3);
248
- const source = ["-f", "lavfi", "-i", `testsrc2=s=640x360:r=${TRANSCODE_FPS}:d=${durationSec}`];
249
- const kf = keyFrameArgs(segmentDurationSec);
250
-
251
- /** @type {string[]} */
252
- let pre = ["-hide_banner", "-loglevel", "error"];
253
- /** @type {string[]} */
254
- let encode;
255
- switch (descriptor.kind) {
256
- case "vaapi":
257
- pre = [...pre, "-vaapi_device", String(descriptor.device)];
258
- encode = ["-vf", "format=nv12,hwupload", "-c:v", "h264_vaapi", "-qp", "24", ...kf];
259
- break;
260
- case "qsv":
261
- pre = [...pre, "-qsv_device", String(descriptor.device)];
262
- encode = ["-vf", "hwupload=extra_hw_frames=16,format=qsv", "-c:v", "h264_qsv", "-global_quality", "24", ...kf];
263
- break;
264
- case "nvenc":
265
- encode = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", "24", "-pix_fmt", "yuv420p", ...kf];
266
- break;
267
- case "v4l2m2m":
268
- encode = ["-pix_fmt", "yuv420p", "-c:v", "h264_v4l2m2m", "-num_capture_buffers", "32", "-b:v", "3M", "-g", String(TRANSCODE_FPS * segmentDurationSec), ...kf];
269
- break;
270
- default:
271
- encode = ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", ...kf];
272
- break;
273
- }
274
-
275
- const hlsOut = [
276
- "-f", "hls",
277
- "-hls_time", String(segmentDurationSec),
278
- "-hls_list_size", "0",
279
- "-hls_flags", "independent_segments",
280
- // fMP4 (CMAF) — matches the runtime pipeline (hls-session-manager).
281
- "-hls_segment_type", "fmp4",
282
- "-hls_fmp4_init_filename", "init.mp4",
283
- "-hls_segment_filename", path.join(outDir, "seg-%03d.m4s"),
284
- path.join(outDir, "index.m3u8")
285
- ];
286
- return [...pre, ...source, ...encode, ...hlsOut];
287
- }
288
-
289
- /**
290
- * Verify the HLS segments produced by the test encode are valid: at least two
291
- * segments exist, and each decodes standalone without errors. A segment that
292
- * does not begin with a keyframe (broken/corrupted output) emits decode errors
293
- * when read on its own, which fails this check.
294
- *
295
- * @param {string} ffmpegBin
296
- * @param {string} outDir
297
- * @returns {Promise<boolean>}
298
- */
299
- async function verifySegmentsDecodeCleanly(ffmpegBin, outDir) {
300
- let files;
301
- try {
302
- files = readdirSync(outDir).filter((n) => /^seg-\d+\.m4s$/.test(n));
303
- } catch {
304
- return false;
305
- }
306
- if (files.length < 2) {
307
- return false;
308
- }
309
- // fMP4: parameter sets (SPS/PPS) live in init.mp4, not in each segment.
310
- // Decode the whole playlist (ffmpeg's own, which references init.mp4 via
311
- // #EXT-X-MAP), so every segment is exercised together with the init. Any
312
- // corrupt / non-conformant segment (e.g. some V4L2 M2M builds emit a stray
313
- // no-picture access unit) surfaces as a decode error here.
314
- const result = await runFfmpeg(
315
- ffmpegBin,
316
- ["-hide_banner", "-loglevel", "error", "-i", path.join(outDir, "index.m3u8"), "-f", "null", "-"],
317
- 12000
318
- );
319
- return result.code === 0 && result.stderr.trim().length === 0;
320
- }
321
-
322
- /**
323
- * Detect the best usable H.264 encoder. Always resolves (falls back to
324
- * software libx264). Each hardware candidate is verified with a real
325
- * test-encode before being selected.
326
- *
327
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, segmentDurationSec?: number }} options
328
- * @returns {Promise<VideoEncoderDescriptor>}
329
- */
330
- export async function detectVideoEncoder({ ffmpegBin, logger, segmentDurationSec = 4 }) {
331
- const log = logger ?? { info: () => {}, warn: () => {} };
332
- const software = softwareDescriptor();
333
-
334
- const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-encoders"], 10000);
335
- if (code !== 0) {
336
- log.warn("hwaccel: could not list ffmpeg encoders; using software libx264");
337
- return software;
338
- }
339
- const has = (name) => stdout.includes(name);
340
-
341
- /** @type {VideoEncoderDescriptor[]} */
342
- const candidates = [];
343
- const renderNodes = listRenderNodes();
344
- if (has("h264_nvenc") && hasNvidiaDevice()) {
345
- candidates.push(nvencDescriptor());
346
- }
347
- if (has("h264_qsv") && renderNodes.length > 0) {
348
- candidates.push(qsvDescriptor(renderNodes[0]));
349
- }
350
- if (has("h264_vaapi") && renderNodes.length > 0) {
351
- candidates.push(vaapiDescriptor(renderNodes[0]));
352
- }
353
- // h264_v4l2m2m (ARM SoC / Raspberry Pi / HA Yellow). It is gated behind the
354
- // strict keyframe-alignment test below, because some V4L2 M2M builds silently
355
- // emit a corrupted / non-IDR-aligned stream; the test rejects those and the
356
- // host falls back to software libx264.
357
- if (has("h264_v4l2m2m") && hasV4l2Device()) {
358
- candidates.push(v4l2m2mDescriptor());
359
- }
360
-
361
- for (const candidate of candidates) {
362
- const dir = mkdtempSync(path.join(os.tmpdir(), "tt-hwtest-"));
363
- let ok = false;
364
- try {
365
- const encoded = await runFfmpeg(
366
- ffmpegBin,
367
- buildEncoderTestArgs(candidate, segmentDurationSec, dir),
368
- 25000
369
- );
370
- if (encoded.code === 0) {
371
- ok = await verifySegmentsDecodeCleanly(ffmpegBin, dir);
372
- }
373
- } finally {
374
- try {
375
- rmSync(dir, { recursive: true, force: true });
376
- } catch {
377
- // best effort
378
- }
379
- }
380
- if (ok) {
381
- log.info(
382
- `hwaccel: using hardware encoder ${candidate.name}` +
383
- `${candidate.device ? ` (${candidate.device})` : ""}`
384
- );
385
- return candidate;
386
- }
387
- log.warn(`hwaccel: ${candidate.name} failed the HLS keyframe-alignment test; skipping`);
388
- }
389
-
390
- log.info("hwaccel: no working hardware encoder; using software libx264");
391
- return software;
392
- }
393
-
394
- /**
395
- * Detect whether this ffmpeg build has the filters needed for the HDR→SDR
396
- * tone-map chain (`zscale`, from libzimg, and `tonemap`). Both are required;
397
- * when either is missing, HDR sources are re-encoded without tone mapping
398
- * (washed-out but playable). Always resolves.
399
- *
400
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
401
- * @returns {Promise<boolean>}
402
- */
403
- export async function detectTonemapSupport({ ffmpegBin, logger }) {
404
- const log = logger ?? { info: () => {}, warn: () => {} };
405
- const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-filters"], 10000);
406
- if (code !== 0) {
407
- log.warn("hwaccel: could not list ffmpeg filters; HDR tone mapping disabled");
408
- return false;
409
- }
410
- // `-filters` prints one filter per line: "... zscale ...", "... tonemap ...".
411
- const hasZscale = /\bzscale\b/.test(stdout);
412
- const hasTonemap = /\btonemap\b/.test(stdout);
413
- const supported = hasZscale && hasTonemap;
414
- log.info(
415
- `hwaccel: HDR tone mapping ${supported ? "available" : "unavailable"} ` +
416
- `(zscale=${hasZscale} tonemap=${hasTonemap})`
417
- );
418
- return supported;
419
- }
420
-
421
-
422
- // The clips the decode cost is fitted from. They ship with the package
423
- // (`assets/calibration/`), cut from Netflix Open Content "Meridian" (CC-BY 4.0)
424
- // — real, grainy live action, because a generated `testsrc2` clip decodes 158 %
425
- // away from a real film where these are 11 % away (measured 2026-08-14).
426
- //
427
- // Three sizes at two bitrates each, with the axes varied INDEPENDENTLY. The set
428
- // this replaced was three clips for three unknowns, two of them at the same
429
- // size: an exact system, which cannot fail visibly. On 2026-08-17 it returned
430
- // `0.007542 × Mpx/s + 0.000000 × Mbit/s + 0.0000 s/s` the bitrate term and
431
- // the constant exactly zero and the prediction on top of it was 1.8-2.2x
432
- // optimistic. Six points leave three spare, so the fit has a residual, and a
433
- // term the data does not determine can be refused instead of published as a
434
- // zero that looks measured. See `assets/calibration/NOTICE.md`.
435
- //
436
- // One set PER CODEC FAMILY, because a family is what the model describes. The
437
- // fit used to be H.264 only, while a video that has to be RE-ENCODED is by
438
- // definition one the browser could not play which is to say HEVC, 10-bit or
439
- // AV1 — and those decode dearer per pixel on the same box. Pricing them with
440
- // H.264 constants is the one case the model is always asked about and was never
441
- // measured on.
442
- //
443
- // A family that has no set of its own is priced with H.264's, which is what
444
- // happened to every family before this; the line says so rather than implying
445
- // it. AV1 has no set yet: the survey of 2026-07-10 found it rare where HEVC was
446
- // 18 % of releases, so it waits for the same treatment.
447
- const CALIBRATION_SETS = {
448
- h264: [
449
- "cal-h264-1080-hi.mp4",
450
- "cal-h264-1080-lo.mp4",
451
- "cal-h264-720-hi.mp4",
452
- "cal-h264-720-lo.mp4",
453
- "cal-h264-480-hi.mp4",
454
- "cal-h264-480-lo.mp4"
455
- ],
456
- hevc: [
457
- "cal-hevc-1080-hi.mp4",
458
- "cal-hevc-1080-lo.mp4",
459
- "cal-hevc-480-hi.mp4",
460
- "cal-hevc-480-lo.mp4"
461
- ],
462
- hevc10: [
463
- "cal-hevc10-1080-hi.mp4",
464
- "cal-hevc10-1080-lo.mp4",
465
- "cal-hevc10-480-hi.mp4",
466
- "cal-hevc10-480-lo.mp4"
467
- ]
468
- };
469
- const CALIBRATION_CLIPS = CALIBRATION_SETS.h264;
470
- const CALIBRATION_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "calibration");
471
- // How wide the measured window must be before the slope is trusted, and how
472
- // long to wait for it at most.
473
- //
474
- // Half a second, and it is the TIMING noise that sets it rather than the amount
475
- // of video: the slope is output time against wall time, both read from the same
476
- // two progress lines, and the jitter in stamping one is milliseconds so half
477
- // a second of window is a fraction of a percent of error on any host. What used
478
- // to make a longer window necessary was the clip restarting inside it, and that
479
- // is gone: the stream is continuous now. Measured 2026-08-22 against the
480
- // continuous-pass truth on a desktop: -3.0 % and +0.6 % at half a second, with
481
- // the readings spread 2-6 %, against -25 % and -33 % for the loop it replaces.
482
- // Half a second also costs the startup about 0.6 s per clip less, which matters
483
- // because every clip of every codec family is paid for before any viewer
484
- // exists.
485
- const DECODE_WINDOW_MIN_SEC = 0.5;
486
- const DECODE_WINDOW_MAX_MS = 8000;
487
-
488
- /**
489
- * Read what a calibration clip IS from the decode run's own output: the
490
- * dimensions, the frame rate and the bitrate ffmpeg reports for it. Read rather
491
- * than declared, so replacing a clip cannot silently invalidate the fit.
492
- *
493
- * @param {string} stderr
494
- * @returns {{ megapixelsPerSecond: number, megabitsPerSecond: number, durationSeconds: number } | null}
495
- */
496
- function parseClipCharacteristics(stderr) {
497
- // The same readers the session manager uses on the same banner — one parser
498
- // per fact, so a second copy cannot drift from the first.
499
- const { width, height } = parseFfmpegVideoDimensions(stderr);
500
- const rate = parseFfmpegVideoFps(stderr);
501
- const seconds = parseFfmpegDurationSeconds(stderr);
502
- const kbps = parseFfmpegBitrateKbps(stderr);
503
- if (!(width > 0) || !(height > 0) || !(rate > 0) || !(seconds > 0) || !(kbps > 0)) {
504
- return null;
505
- }
506
- return {
507
- megapixelsPerSecond: (width * height * rate) / 1e6,
508
- megabitsPerSecond: kbps / 1000,
509
- durationSeconds: seconds
510
- };
511
- }
512
-
513
- /**
514
- * Measure what DECODING costs on this host, as seconds of work per second of
515
- * video, and solve it into three host constants:
516
- *
517
- * decodeCost = a × Mpixel/s + b × Mbit/s + c
518
- *
519
- * Why it exists: the preset benchmark below measures ENCODING only, and a
520
- * re-encode pays for both halves. Measured 2026-08-14 on the addon host, that
521
- * omission made the budget offer a 240p rung it then ran at 0.39-0.95× the
522
- * benchmark said the host cleared the bar 2.5× over. With the decode term the
523
- * same file predicts within 4.8 %; without it the error on that rung was 209 %.
524
- *
525
- * The constants are properties of the HOST, so this runs once at startup (about
526
- * 5 s on a CM4) and any source is then priced from figures the probe already
527
- * has nothing is added to a session's cold start.
528
- *
529
- * They are also properties of the CODEC, and the clips are H.264: HEVC, AV1 and
530
- * 10-bit decode dearer per pixel on the same machine, and a source that has to
531
- * be re-encoded is by definition one this browser could not play, which is
532
- * usually not H.264. So the fit is optimistic exactly there. Closing that needs
533
- * clips in those codecs, and is its own roadmap item.
534
- *
535
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} options
536
- * @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
537
- */
538
- /**
539
- * What a second job costs on this host, measured rather than assumed.
540
- *
541
- * The budget adds seconds of work per second of content — this encode, plus
542
- * that decode, plus what is already committed and the addon host contradicted
543
- * that directly on 2026-08-18: decoding ran at 2.10-2.25x alone, 0.79-0.90x
544
- * with one encoder beside it and 0.56-0.64x with two. The same work costs 2.
545
- * more for having company. Heat is not the cause (the hot idle machine was the
546
- * fastest reading of all); four cores sharing one path to memory is.
547
- *
548
- * So it is measured the way everything else here is: the same clip decoded
549
- * alone, then decoded again while an encoder of the same clip runs beside it.
550
- * The ratio is the penalty. The encoder is stopped as soon as the reading is
551
- * taken, and the whole thing costs one decode plus one short encode.
552
- *
553
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string, upTo?: number }} options
554
- * @returns {Promise<Map<number, number> | null>} Penalties by how many other
555
- * jobs were running, or null when the readings could not be taken.
556
- */
557
- export async function benchmarkContention({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR, upTo = 2 }) {
558
- const log = logger ?? { info: () => {}, warn: () => {} };
559
- // The cheapest clip in the set: this measures the MACHINE's behaviour under
560
- // company, not the clip's own cost, so the smallest one says it soonest.
561
- const clip = path.join(clipsDir, "cal-h264-480-lo.mp4");
562
- const startedAt = Date.now();
563
- // Lifted once and decoded three times from the same bytes. Going through
564
- // `measureDecodeSlope` lifted it again for every reading — three process
565
- // starts on a path that is awaited before the proxy's tunnel opens, for a
566
- // remux whose result had not changed.
567
- const streams = await extractFamilyStreams(ffmpegBin, [clip], "h264");
568
- const stream = streams?.[0];
569
- if (!stream) {
570
- log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
571
- return null;
572
- }
573
- const alone = await decodePipedStream(ffmpegBin, stream, log);
574
- if (!alone?.speed) {
575
- log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
576
- return null;
577
- }
578
- /** @type {Array<{ others: number, speed: number }>} */
579
- const beside = [];
580
- /** @type {import("node:child_process").ChildProcess[]} */
581
- const load = [];
582
- try {
583
- for (let others = 1; others <= Math.max(1, upTo); others += 1) {
584
- load.push(
585
- spawn(
586
- ffmpegBin,
587
- [
588
- "-hide_banner", "-loglevel", "error", "-nostats",
589
- "-stream_loop", "-1", "-i", clip,
590
- "-an", "-c:v", "libx264", "-preset", "fast", "-f", "null", "-"
591
- ],
592
- { stdio: ["ignore", "ignore", "ignore"], windowsHide: true }
593
- )
594
- );
595
- // Let the encoder reach its own speed before reading anything: an encode
596
- // measured in its first moments is measuring the process starting.
597
- await new Promise((resolve) => {
598
- setTimeout(resolve, 2_000);
599
- });
600
- const withCompany = await decodePipedStream(ffmpegBin, stream, log);
601
- if (withCompany?.speed) {
602
- beside.push({ others, speed: withCompany.speed });
603
- }
604
- }
605
- } finally {
606
- for (const child of load) {
607
- try {
608
- child.kill("SIGKILL");
609
- } catch {
610
- // Already gone: the reading is what mattered, and nothing else uses it.
611
- }
612
- }
613
- }
614
- const penalties = penaltiesFrom(alone.speed, beside);
615
- if (!penalties) {
616
- log.warn("hwaccel: contention readings said nothing; costs will be added as though jobs were independent");
617
- return null;
618
- }
619
- log.info(
620
- `hwaccel: a second job costs ${[...penalties.entries()]
621
- .map(([others, penalty]) => `${penalty.toFixed(2)}x beside ${others}`)
622
- .join(", ")} ` +
623
- `(decode alone ${alone.speed.toFixed(2)}x, ` +
624
- `${beside.map((reading) => `${reading.speed.toFixed(2)}x beside ${reading.others}`).join(", ")}, ` +
625
- `measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
626
- );
627
- return penalties;
628
- }
629
-
630
- export async function benchmarkDecodeCost({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
631
- const log = logger ?? { info: () => {}, warn: () => {} };
632
- const startedAllAt = Date.now();
633
- /** @type {Record<string, { pixelTerm: number, bitrateTerm: number, constantTerm: number }>} */
634
- const families = {};
635
- for (const [family, clips] of Object.entries(CALIBRATION_SETS)) {
636
- const fitted = await fitOneFamily({ ffmpegBin, log, clipsDir, family, clips });
637
- if (fitted) {
638
- families[family] = fitted;
639
- }
640
- }
641
- if (!families.h264) {
642
- // H.264 is the family every other one falls back to, so without it there is
643
- // no model at all rather than a partial one. Which families DID fit is said
644
- // anyway: on a fast host the H.264 clips decode at 20-80x and the readings
645
- // stop being ordered measured 2026-08-20 on a desktop, 1080p at 9.35
646
- // Mbit/s costing 0.0307 s/s against 720p at 9.94 costing 0.0472, which is
647
- // not a thing a decoder does — so a failure here is a measurement problem
648
- // and not a missing file, and the line has to let those be told apart.
649
- log.warn(
650
- "hwaccel: decode cost unknown — the H.264 clips did not fit" +
651
- (Object.keys(families).length > 0
652
- ? `, though ${Object.keys(families).join(" and ")} did`
653
- : "")
654
- );
655
- return null;
656
- }
657
- const missing = Object.keys(CALIBRATION_SETS).filter((family) => !families[family]);
658
- log.info(
659
- `hwaccel: decode cost measured for ${Object.keys(families).join(", ")}` +
660
- (missing.length > 0 ? `; ${missing.join(" and ")} priced as H.264` : "") +
661
- ` (in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
662
- );
663
- return { families, ...families.h264 };
664
- }
665
-
666
- /**
667
- * Fit one codec family's decode cost from its own clips.
668
- *
669
- * @param {{ ffmpegBin: string, log: { info: Function, warn: Function }, clipsDir: string, family: string, clips: string[] }} params
670
- * @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
671
- */
672
- async function fitOneFamily({ ffmpegBin, log, clipsDir, family, clips }) {
673
- const startedAllAt = Date.now();
674
- /** @type {Array<{ megapixelsPerSecond: number, megabitsPerSecond: number, costSecondsPerSecond: number }>} */
675
- const samples = [];
676
- // Every clip of the family is lifted out of its container FIRST, in one
677
- // ffmpeg run. See `extractFamilyStreams` for why one run rather than one per
678
- // clip, and why before the measurements rather than beside them.
679
- const streams = await extractFamilyStreams(
680
- ffmpegBin,
681
- clips.map((clip) => path.join(clipsDir, clip)),
682
- family
683
- );
684
- if (!streams) {
685
- log.warn(
686
- `hwaccel: ${family} cannot be lifted out of its container — no Annex-B filter is mapped for it, ` +
687
- `so its clips were never measured`
688
- );
689
- return null;
690
- }
691
- for (const [index, clip] of clips.entries()) {
692
- const stream = streams[index];
693
- const measured = stream ? await decodePipedStream(ffmpegBin, stream, log) : null;
694
- if (!measured?.speed) {
695
- log.warn(
696
- `hwaccel: decode benchmark "${clip}" said nothing; ${family} not measured` +
697
- (measured?.error ? ` — ${measured.error}` : " — the clip could not be lifted out of its container")
698
- );
699
- return null;
700
- }
701
- const cost = 1 / measured.speed;
702
- samples.push({
703
- megapixelsPerSecond: measured.megapixelsPerSecond,
704
- megabitsPerSecond: measured.megabitsPerSecond,
705
- costSecondsPerSecond: cost
706
- });
707
- log.info(
708
- `hwaccel: decode "${clip}" ${measured.megapixelsPerSecond.toFixed(1)} Mpx/s ` +
709
- `${measured.megabitsPerSecond.toFixed(2)} Mbit/s -> ${measured.speed.toFixed(1)}x ` +
710
- `(cost ${cost.toFixed(4)} s/s, over ${measured.windowSec.toFixed(1)}s of decoding)`
711
- );
712
- }
713
- const fitted = fitDecodeCost(samples);
714
- if (!fitted) {
715
- log.warn(`hwaccel: ${family} decode cost could not be fitted to these measurements`);
716
- return null;
717
- }
718
- log.info(
719
- `hwaccel: ${family} decode cost = ${fitted.pixelTerm.toFixed(6)} × Mpx/s + ${fitted.bitrateTerm.toFixed(6)} × Mbit/s ` +
720
- `+ ${fitted.constantTerm.toFixed(4)} s/s (${fitted.shape} from ${fitted.samples} clips, ` +
721
- `typical disagreement ${fitted.residualRms.toFixed(4)} s/s` +
722
- // Named rather than implied: a zero in the line above means "not
723
- // measured" for a dropped term and "measured to be nothing" otherwise,
724
- // and those are different claims.
725
- (fitted.dropped.length > 0 ? `, ${fitted.dropped.join(" and ")} not determined by these clips` : "") +
726
- `, measured in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
727
- );
728
- return { pixelTerm: fitted.pixelTerm, bitrateTerm: fitted.bitrateTerm, constantTerm: fitted.constantTerm };
729
- }
730
-
731
- /**
732
- * The bitstream filter and demuxer that turn a clip's video track into a
733
- * continuous elementary stream, by codec family.
734
- *
735
- * H.264 and HEVC in MP4 keep their parameter sets in the container's `avcC` /
736
- * `hvcC` and their access units length-prefixed; Annex-B carries them inline,
737
- * with start codes, which is what makes plain byte concatenation a valid
738
- * stream. That is the property this whole measurement rests on.
739
- */
740
- const ANNEX_B_BY_FAMILY = {
741
- h264: { filter: "h264_mp4toannexb", demuxer: "h264" },
742
- hevc: { filter: "hevc_mp4toannexb", demuxer: "hevc" },
743
- hevc10: { filter: "hevc_mp4toannexb", demuxer: "hevc" }
744
- };
745
-
746
- /**
747
- * The last complaint in an ffmpeg stderr, for a line that has to say why.
748
- *
749
- * @param {string} stderr
750
- * @returns {string}
751
- */
752
- function lastErrorLine(stderr) {
753
- const lines = String(stderr ?? "")
754
- .split(/\r?\n/)
755
- .map((line) => line.trim())
756
- .filter((line) => line.length > 0);
757
- return lines[lines.length - 1] ?? "";
758
- }
759
-
760
- /**
761
- * How long the lift may take before it is abandoned. It is a remux of a few
762
- * megabytes, so this is not a budget — it is the difference between a startup
763
- * that reports a failure and one that never finishes. Every other ffmpeg run in
764
- * this file has such a bound; this one did not, and it is awaited before the
765
- * proxy's tunnel opens.
766
- */
767
- const EXTRACT_TIMEOUT_MS = 20_000;
768
-
769
- /**
770
- * Lift a whole family's clips out of their containers, as Annex-B elementary
771
- * streams, in ONE ffmpeg run.
772
- *
773
- * No re-encoding the frames are copied so the work itself is trivial and
774
- * the cost is almost entirely the process. Doing one process per clip added
775
- * 11 s to the startup here (fourteen clips at about 0.83 s each), and running
776
- * them concurrently did not help: six at once took 4.75 s against 0.89 s for
777
- * one, so the machine serialises them. One run with many inputs and many
778
- * outputs costs one process.
779
- *
780
- * The outputs go to temporary files because several outputs cannot share one
781
- * pipe; they are read into memory and deleted immediately, and nothing about
782
- * this measurement is kept between runs.
783
- *
784
- * Before the measurements, never beside them: a remux running next to a decode
785
- * is a second job on the machine, and this benchmark exists to find out what
786
- * ONE job costs here.
787
- *
788
- * @param {string} ffmpegBin
789
- * @param {string[]} clipPaths
790
- * @param {string} family
791
- * @returns {Promise<Array<{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number } | null> | null>}
792
- * One entry per clip, in order; null when the family cannot be lifted at all.
793
- */
794
- async function extractFamilyStreams(ffmpegBin, clipPaths, family) {
795
- const shape = ANNEX_B_BY_FAMILY[family];
796
- // A family with no mapping is a hard failure, not a silent fallback to
797
- // H.264's filter. AV1 has no Annex-B form at all (its packaging is OBU), and
798
- // MPEG-2 and VC-1 have no `*_mp4toannexb` filter so the three families the
799
- // roadmap plans next cannot come through here, and finding that out as
800
- // "the clip failed" would send the reader after the clip.
801
- if (!shape) {
802
- return null;
803
- }
804
- const workDir = await mkdtemp(path.join(os.tmpdir(), "ttv-calibration-"));
805
- const outputs = clipPaths.map((_, index) => path.join(workDir, `stream-${index}.${shape.demuxer}`));
806
- /** @type {string[]} */
807
- const args = ["-hide_banner", "-loglevel", "info", "-nostats", "-y"];
808
- for (const clipPath of clipPaths) {
809
- args.push("-i", clipPath);
810
- }
811
- for (const [index, output] of outputs.entries()) {
812
- args.push("-map", `${index}:v:0`, "-c:v", "copy", "-bsf:v", shape.filter, "-f", shape.demuxer, output);
813
- }
814
- const stderr = await runCapturingStderr(ffmpegBin, args, EXTRACT_TIMEOUT_MS);
815
- try {
816
- if (stderr === null) {
817
- return null;
818
- }
819
- // One banner block per input, in the order they were given. Read rather
820
- // than declared, so replacing a clip cannot silently invalidate the fit
821
- // that rests on it.
822
- const blocks = splitInputBlocks(stderr, clipPaths.length);
823
- return await Promise.all(clipPaths.map(async (_, index) => {
824
- const block = blocks[index];
825
- if (!block) {
826
- return null;
827
- }
828
- const clipInfo = parseClipCharacteristics(block);
829
- const fps = parseFfmpegVideoFps(block);
830
- if (!clipInfo || !(fps > 0)) {
831
- return null;
832
- }
833
- let bytes;
834
- try {
835
- bytes = await readFile(outputs[index]);
836
- } catch {
837
- return null;
838
- }
839
- if (bytes.length === 0) {
840
- return null;
841
- }
842
- return {
843
- bytes,
844
- demuxer: shape.demuxer,
845
- megapixelsPerSecond: clipInfo.megapixelsPerSecond,
846
- megabitsPerSecond: clipInfo.megabitsPerSecond,
847
- fps
848
- };
849
- }));
850
- } finally {
851
- await rm(workDir, { recursive: true, force: true }).catch(() => {});
852
- }
853
- }
854
-
855
- /**
856
- * The part of an ffmpeg banner describing each input, in order.
857
- *
858
- * ffmpeg prints one `Input #N, …` block per input and then the stream mapping;
859
- * the parsers here read a single input's facts, so they are given a single
860
- * input's text rather than the whole banner.
861
- *
862
- * @param {string} stderr
863
- * @param {number} count
864
- * @returns {string[]}
865
- */
866
- function splitInputBlocks(stderr, count) {
867
- /** @type {string[]} */
868
- const blocks = [];
869
- for (let index = 0; index < count; index += 1) {
870
- const from = stderr.indexOf(`Input #${index},`);
871
- if (from < 0) {
872
- blocks.push("");
873
- continue;
874
- }
875
- const nextInput = stderr.indexOf(`Input #${index + 1},`, from);
876
- const mapping = stderr.indexOf("Stream mapping:", from);
877
- const ends = [nextInput, mapping].filter((at) => at > from);
878
- blocks.push(stderr.slice(from, ends.length > 0 ? Math.min(...ends) : stderr.length));
879
- }
880
- return blocks;
881
- }
882
-
883
- /**
884
- * Run ffmpeg to completion and return its stderr, or null when it failed or
885
- * outlasted its bound.
886
- *
887
- * @param {string} ffmpegBin
888
- * @param {string[]} args
889
- * @param {number} timeoutMs
890
- * @returns {Promise<string | null>}
891
- */
892
- function runCapturingStderr(ffmpegBin, args, timeoutMs) {
893
- return new Promise((resolve) => {
894
- let stderr = "";
895
- let settled = false;
896
- let child;
897
- const settle = (value) => {
898
- if (settled) {
899
- return;
900
- }
901
- settled = true;
902
- clearTimeout(timer);
903
- try {
904
- child?.kill("SIGKILL");
905
- } catch {
906
- // already gone
907
- }
908
- resolve(value);
909
- };
910
- const timer = setTimeout(() => settle(null), timeoutMs);
911
- try {
912
- child = spawn(ffmpegBin, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
913
- } catch {
914
- settle(null);
915
- return;
916
- }
917
- child.stderr.on("data", (chunk) => {
918
- stderr += String(chunk);
919
- });
920
- child.on("error", () => settle(null));
921
- child.on("close", (code) => settle(code === 0 ? stderr : null));
922
- });
923
- }
924
-
925
- /**
926
- * Measure how fast this host DECODES a clip, from ffmpeg's own report of how
927
- * much video it has processed.
928
- *
929
- * Two things are deliberately outside the measurement.
930
- *
931
- * **The process starting.** Wall-clock around the process cannot answer this:
932
- * starting ffmpeg costs about a second, and on a quick machine a five-second
933
- * clip decodes in a tenth of that, so the measurement would be of the program
934
- * starting. Progress lines arrive AFTER it has started, and the slope between
935
- * two of them — video processed against time taken — contains no part of the
936
- * startup by construction.
937
- *
938
- * **The clip restarting.** This used to loop the clip with `-stream_loop -1`,
939
- * and a loop is not free: measured 2026-08-22 on a desktop, a restart costs
940
- * 0.03 s on the 480p clip and 0.12 s on the 1080p one — the decoder tearing
941
- * down and re-allocating its frame buffers, which is why the price rises with
942
- * the picture. A five-second clip decoded at 55x restarts eleven times a
943
- * second, so that cost DOMINATED the reading: the same clips measured 53.7x
944
- * looped against 80.3x in one continuous pass, and 11.8x against 15.8x. Worse,
945
- * the bias is not shared — it depends on the clip's own resolution and on how
946
- * fast the host is — so it does not cancel out of the fit, it tilts it. That is
947
- * the fast-host failure recorded on 2026-08-20, where 1080p read cheaper than
948
- * 720p, which is not a thing a decoder does.
949
- *
950
- * So the clip is fed to the decoder as ONE stream instead. An Annex-B
951
- * elementary stream carries its parameter sets inline, so writing the same
952
- * bytes again is simply more stream the decoder never re-initialises, and
953
- * there is no restart inside the window to measure. Verified against the
954
- * continuous-pass truth on the same host: -0.2 % and -5.5 %, against -25 % and
955
- * -33 % for the loop. Nothing is written to disk and the process is killed as
956
- * soon as the window is wide enough.
957
- *
958
- * Exported because the property that broke here is checkable and was not being
959
- * checked: a bigger picture must cost more than a smaller one of the same
960
- * bitrate, and under the loop it did not.
961
- *
962
- * @param {string} ffmpegBin
963
- * @param {string} clipPath
964
- * @param {string} [family="h264"]
965
- * @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
966
- */
967
- export async function measureDecodeSlope(ffmpegBin, clipPath, family = "h264") {
968
- const streams = await extractFamilyStreams(ffmpegBin, [clipPath], family);
969
- const stream = streams?.[0];
970
- if (!stream) {
971
- return null;
972
- }
973
- const measured = await decodePipedStream(ffmpegBin, stream);
974
- return measured?.speed ? measured : null;
975
- }
976
-
977
- /**
978
- * Decode an elementary stream fed from memory, and report the slope.
979
- *
980
- * @param {string} ffmpegBin
981
- * @param {{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number }} stream
982
- * @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
983
- */
984
- function decodePipedStream(ffmpegBin, stream, log = { info: () => {}, warn: () => {} }) {
985
- return new Promise((resolve) => {
986
- const args = [
987
- "-hide_banner", "-loglevel", "error", "-nostats",
988
- // A raw stream states no frame rate, so the one the container declared is
989
- // given back to it. It decides how output time advances, and therefore
990
- // what "seconds of video per second of clock" means.
991
- "-f", stream.demuxer, "-framerate", String(stream.fps), "-i", "pipe:0",
992
- "-an", "-f", "null", "-",
993
- "-progress", "pipe:1"
994
- ];
995
- /** @type {Array<{ wallSec: number, outSec: number }>} */
996
- const samples = [];
997
- let stdout = "";
998
- // Kept because this path depends on three things the old one did not: the
999
- // raw demuxer accepting the frame rate, the bitstream filter having
1000
- // produced something parsable, and the fed concatenation being decodable.
1001
- // Without it the only trace of any of those failing is "said nothing".
1002
- let stderr = "";
1003
- let settled = false;
1004
- let child;
1005
- const startedAt = Date.now();
1006
- // Whether the FEED, not the decoder, could be what this reading measures
1007
- // (item 4(d2)). `child.stdin.write()` returning false was tried as the
1008
- // signal never once true would mean this process was never ahead of the
1009
- // pipe and measured false on every reading taken while writing this,
1010
- // including clips this same host decodes at 15-80x with room to spare, so
1011
- // it does not discriminate: `write()`'s return value tracks Node's own
1012
- // internal watermark against the size of what was just handed to it, not
1013
- // real drain state, and answered "no slack" identically whether the pipe
1014
- // or the decoder was the true limit. Rather than publish a verdict that
1015
- // reads the same in both cases, only the byte count is kept, for the
1016
- // MB/s figure below a number to read, not a boolean to trust.
1017
- let bytesWritten = 0;
1018
- const finish = () => {
1019
- if (settled) {
1020
- return;
1021
- }
1022
- settled = true;
1023
- clearTimeout(timer);
1024
- try {
1025
- child?.stdin?.destroy();
1026
- } catch {
1027
- // already gone
1028
- }
1029
- try {
1030
- child?.kill("SIGKILL");
1031
- } catch {
1032
- // already gone
1033
- }
1034
- // The first sample still carries the startup — it reports whatever was
1035
- // processed while the process was coming up. Everything is measured from
1036
- // the second onwards.
1037
- const first = samples[1];
1038
- const last = samples[samples.length - 1];
1039
- if (!first || !last) {
1040
- resolve({ error: lastErrorLine(stderr) || "the decoder reported no progress" });
1041
- return;
1042
- }
1043
- const windowSec = last.wallSec - first.wallSec;
1044
- const producedSec = last.outSec - first.outSec;
1045
- if (!(windowSec >= DECODE_WINDOW_MIN_SEC) || !(producedSec > 0)) {
1046
- resolve({ error: lastErrorLine(stderr) || `the window was ${windowSec.toFixed(2)}s of ${producedSec.toFixed(2)}s produced` });
1047
- return;
1048
- }
1049
- const speed = producedSec / windowSec;
1050
- // Diagnostic only — logged, not acted on. Both figures are taken over the
1051
- // SAME window the speed itself is: bytesWritten is snapshotted alongside
1052
- // every progress sample, so this compares like against like rather than
1053
- // the achieved rate over the whole run (which starts before the first
1054
- // kept sample and reads systematically low against the window's own
1055
- // rate for no reason but that mismatch measured while building this).
1056
- const windowBytes = last.bytesWritten - first.bytesWritten;
1057
- const achievedMBps = windowSec > 0 ? windowBytes / windowSec / 1e6 : 0;
1058
- const requiredMBps = ((stream.megabitsPerSecond * 1e6) / 8) * speed / 1e6;
1059
- // "Far apart" is stated, not left to the reader to eyeball: outside a
1060
- // factor of 1.5 either way is bigger than the write-timing slop this
1061
- // comparison carries on a healthy reading.
1062
- const farApart = requiredMBps > 0 && (achievedMBps / requiredMBps < 1 / 1.5 || achievedMBps / requiredMBps > 1.5);
1063
- log.info(
1064
- `hwaccel: decode pipe fed ${achievedMBps.toFixed(1)} MB/s, ${requiredMBps.toFixed(1)} MB/s ` +
1065
- `needed for ${speed.toFixed(2)}x` +
1066
- (farApart ? " — far enough apart to be worth a second look" : "")
1067
- );
1068
- resolve({
1069
- speed,
1070
- windowSec,
1071
- megapixelsPerSecond: stream.megapixelsPerSecond,
1072
- megabitsPerSecond: stream.megabitsPerSecond,
1073
- pipeThroughputMBps: achievedMBps
1074
- });
1075
- };
1076
- const timer = setTimeout(finish, DECODE_WINDOW_MAX_MS);
1077
- try {
1078
- child = spawn(ffmpegBin, args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1079
- } catch (error) {
1080
- clearTimeout(timer);
1081
- settled = true;
1082
- resolve({ error: error instanceof Error ? error.message : String(error) });
1083
- return;
1084
- }
1085
- child.stderr.on("data", (chunk) => {
1086
- stderr += String(chunk);
1087
- });
1088
- // Keep the decoder fed. `write` returning false means the pipe is full, and
1089
- // the next copy goes on the `drain` — so the decoder is never starved and
1090
- // this process never buffers more than the pipe holds.
1091
- const writeOnce = () => {
1092
- const accepted = child.stdin.write(stream.bytes);
1093
- bytesWritten += stream.bytes.length;
1094
- return accepted;
1095
- };
1096
- const feed = () => {
1097
- while (!settled && child.stdin.writable && writeOnce()) {
1098
- // Written straight through; go round again.
1099
- }
1100
- };
1101
- child.stdin.on("drain", feed);
1102
- // The kill closes the pipe under the writer; that is the intended end.
1103
- child.stdin.on("error", () => {});
1104
- child.stdout.on("data", (chunk) => {
1105
- stdout += String(chunk);
1106
- let newline = stdout.indexOf("\n");
1107
- while (newline >= 0) {
1108
- const line = stdout.slice(0, newline).trim();
1109
- stdout = stdout.slice(newline + 1);
1110
- if (line.startsWith("out_time_ms=")) {
1111
- const microseconds = Number(line.slice("out_time_ms=".length));
1112
- if (Number.isFinite(microseconds)) {
1113
- samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec: microseconds / 1e6, bytesWritten });
1114
- }
1115
- }
1116
- newline = stdout.indexOf("\n");
1117
- }
1118
- if (samples.length >= 2 && samples[samples.length - 1].wallSec - samples[1].wallSec >= DECODE_WINDOW_MIN_SEC) {
1119
- finish();
1120
- }
1121
- });
1122
- child.on("error", (error) => {
1123
- if (settled) {
1124
- return;
1125
- }
1126
- clearTimeout(timer);
1127
- settled = true;
1128
- try {
1129
- child?.stdin?.destroy();
1130
- } catch {
1131
- // already gone
1132
- }
1133
- try {
1134
- child?.kill("SIGKILL");
1135
- } catch {
1136
- // already gone
1137
- }
1138
- resolve({ error: error instanceof Error ? error.message : String(error) });
1139
- });
1140
- child.on("close", finish);
1141
- feed();
1142
- });
1143
- }
1144
-
1145
-
1146
- /**
1147
- * How many times realtime this host can DECODE a source of these
1148
- * characteristics, from the startup fit. `null` when the fit is unavailable or
1149
- * the source figures are not known.
1150
- *
1151
- * @param {{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null} model
1152
- * @param {{ megapixelsPerSecond: number, megabitsPerSecond: number }} source
1153
- * @returns {number | null}
1154
- */
1155
- export function decodeSpeedFor(model, source) {
1156
- if (!model) {
1157
- return null;
1158
- }
1159
- const pixels = Number(source?.megapixelsPerSecond);
1160
- const bits = Number(source?.megabitsPerSecond);
1161
- if (!Number.isFinite(pixels) || pixels <= 0 || !Number.isFinite(bits) || bits < 0) {
1162
- return null;
1163
- }
1164
- const cost = model.pixelTerm * pixels + model.bitrateTerm * bits + model.constantTerm;
1165
- if (!(cost > 0)) {
1166
- return null;
1167
- }
1168
- return 1 / cost;
1169
- }
1170
-
1171
- /**
1172
- * How many times realtime a re-encode of this source at this output pixel rate
1173
- * would run: decoding and encoding share the machine, so their costs add and
1174
- * their speeds combine as
1175
- *
1176
- * 1 / (1/decodeSpeed + 1/encodeSpeed)
1177
- *
1178
- * Checked 2026-08-14 on the rung that broke playback: 1/(1/2.31 + 1/5.99) =
1179
- * 1.67× against 1.48× measured. With no decode fit this falls back to the
1180
- * encode speed alone — which is what the budget did before, and which
1181
- * overestimated that rung five to eleven times.
1182
- *
1183
- * @param {{ decodeModel: { pixelTerm: number, bitrateTerm: number, constantTerm: number } | null, encodePixelsPerSec: number, outputPixelsPerSec: number, source: { megapixelsPerSecond: number, megabitsPerSecond: number } | null }} params
1184
- * @returns {number | null}
1185
- */
1186
- export function predictedRealtimeSpeed({
1187
- decodeModel,
1188
- encodePixelsPerSec,
1189
- outputPixelsPerSec,
1190
- source,
1191
- observedDecodeCostSec = null
1192
- }) {
1193
- if (!Number.isFinite(encodePixelsPerSec) || encodePixelsPerSec <= 0) {
1194
- return null;
1195
- }
1196
- if (!Number.isFinite(outputPixelsPerSec) || outputPixelsPerSec <= 0) {
1197
- return null;
1198
- }
1199
- const encodeSpeed = encodePixelsPerSec / outputPixelsPerSec;
1200
- // What this very file has been seen to cost, when it has been: the clips are
1201
- // H.264 and a source that has to be re-encoded usually is not, so a figure
1202
- // taken from the encoder actually running on THIS source beats any model of
1203
- // a stand-in. It arrives seconds into playback and replaces the estimate.
1204
- const decodeSpeed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
1205
- ? 1 / observedDecodeCostSec
1206
- : (source ? decodeSpeedFor(decodeModel, source) : null);
1207
- if (decodeSpeed === null) {
1208
- return encodeSpeed;
1209
- }
1210
- return 1 / (1 / decodeSpeed + 1 / encodeSpeed);
1211
- }
1212
-
1213
- /**
1214
- * Whether this host can hold realtime, with the margin, while re-encoding this
1215
- * source to this output pixel rate — and the predicted speed either way, so a
1216
- * refusal can say what it refused on.
1217
- *
1218
- * The encoder figure is the FASTEST benchmarked preset: it is the best this
1219
- * host can do, so a rung it cannot hold cannot be held at any quality setting.
1220
- *
1221
- * @param {{ benchmark: Array<{ preset: string, pixelsPerSec: number }>, decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, outputPixelsPerSec: number, requiredSpeed?: number | null }} params
1222
- * @returns {{ speed: number | null, sustainable: boolean }}
1223
- */
1224
- export function canSustainOutput({
1225
- benchmark,
1226
- decodeModel = null,
1227
- source = null,
1228
- outputPixelsPerSec,
1229
- observedDecodeCostSec = null,
1230
- concurrentCostSec = 0,
1231
- requiredSpeed = null
1232
- }) {
1233
- if (!Array.isArray(benchmark) || benchmark.length === 0) {
1234
- // Nothing measured on this host: the budget cannot refuse what it cannot
1235
- // price, and refusing everything would leave a viewer with no rung at all.
1236
- return { speed: null, sustainable: true };
1237
- }
1238
- const observed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
1239
- ? observedDecodeCostSec
1240
- : null;
1241
- if (observed === null && !isDecodePriced({ decodeModel, source })) {
1242
- // An encoder-only figure was several times too optimistic on the rung this
1243
- // check exists for, so it is not fit to refuse anything. Without the decode
1244
- // term the ladder is offered whole, exactly as it was before.
1245
- return { speed: null, sustainable: true };
1246
- }
1247
- const alone = predictedRealtimeSpeed({
1248
- decodeModel,
1249
- encodePixelsPerSec: cheapestPresetPixelsPerSec(benchmark),
1250
- outputPixelsPerSec,
1251
- source,
1252
- observedDecodeCostSec: observed
1253
- });
1254
- // What ELSE will be running while this rung is. A rung is never the only
1255
- // thing on the machine: the picture it accompanies is being copied or
1256
- // encoded, an audio track may have its own encoder, and a warm-up is two
1257
- // encoders by design. Measured on the addon host, a copy alone takes about an
1258
- // eighth of the machine per second of video, and the field case of
1259
- // 2026-08-15 adds up exactly: 0.125 for the copy plus ~1.05 for the rung is
1260
- // more than the one second per second the machine has, which is what was
1261
- // observed.
1262
- //
1263
- // Zero when nothing else is known to be running, or when nothing has been
1264
- // measured yet then this is a LOWER bound on the cost and the check is as
1265
- // permissive as it was before.
1266
- const speed = alone === null || !(concurrentCostSec > 0)
1267
- ? alone
1268
- : 1 / (1 / alone + concurrentCostSec);
1269
- if (speed === null) {
1270
- return { speed: null, sustainable: true };
1271
- }
1272
- return { speed, sustainable: speed >= speedBar(requiredSpeed) };
1273
- }
1274
-
1275
- /**
1276
- * The speed a step has to reach to be worth offering.
1277
- *
1278
- * Realtime is not enough on its own: a step that produces exactly one second
1279
- * per second never recovers the seconds lost while its reader waits for the
1280
- * swarm, so it survives its own supply only if what it gains between
1281
- * interruptions covers what one interruption costs. That is measured per file
1282
- * and per swarm by the reader `1 + worst wait / median interval`, in
1283
- * `supply-margin.js` and on the field torrent of 2026-08-17 it came to 1.67
1284
- * against the 1.5 that used to stand here, and to 4.04-8.14 on a torrent whose
1285
- * swarm no encoder could have kept up with.
1286
- *
1287
- * Where that figure does not exist yet fewer than two interruptions measured
1288
- * the bar is realtime. It is the one thing that can be said without
1289
- * measuring the swarm, and the offer is restated as soon as the reader has
1290
- * something to say.
1291
- *
1292
- * @param {number | null | undefined} requiredSpeed - What this file's own
1293
- * interruptions demand, when they have been measured.
1294
- * @returns {number}
1295
- */
1296
- export function speedBar(requiredSpeed) {
1297
- return Number.isFinite(requiredSpeed) && requiredSpeed > REALTIME ? requiredSpeed : REALTIME;
1298
- }
1299
-
1300
- /**
1301
- * The bar for a cost description — the supply's demand where decoding is
1302
- * priced, and never below the unpriced-decode bar where it is not.
1303
- *
1304
- * @param {{ decodeModel?: object | null, source?: object | null, observedDecodeCostSec?: number | null, requiredSpeed?: number | null }} cost
1305
- * @returns {number}
1306
- */
1307
- function barFor(cost) {
1308
- const measured = speedBar(cost?.requiredSpeed);
1309
- return isDecodePriced(cost) ? measured : Math.max(UNPRICED_DECODE_BAR, measured);
1310
- }
1311
-
1312
- /**
1313
- * Benchmark software libx264 presets on this host. Encodes a short synthetic
1314
- * clip at a fixed reference resolution with each preset and measures encoder
1315
- * throughput in pixels/second. The session manager uses this to pick, per
1316
- * stream, the highest-quality preset that still encodes the actual
1317
- * (source-capped) resolution faster than realtime.
1318
- *
1319
- * Runs once at startup; bounded by a per-encode timeout. Presets that fail are
1320
- * omitted from the result.
1321
- *
1322
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
1323
- * @returns {Promise<Array<{ preset: string, pixelsPerSec: number }>>} Ordered slowest→fastest.
1324
- */
1325
- export async function benchmarkSoftwarePresets({ ffmpegBin, logger }) {
1326
- const log = logger ?? { info: () => {}, warn: () => {} };
1327
-
1328
- // REAL footage, decoded ONCE into raw frames, and the presets are then timed
1329
- // on those frames.
1330
- //
1331
- // Two reasons, both measured. The pattern this replaced (`testsrc2`) has flat
1332
- // areas and no grain and encodes 1.23x cheaper than film on the same machine
1333
- // and preset an error that always points at offering a rung the host cannot
1334
- // hold. And feeding a compressed clip to each preset instead would put
1335
- // decoding and scaling inside the measurement: subtracting them afterwards
1336
- // compares a wall clock that includes process startup against a decode figure
1337
- // measured to exclude it, while inside one ffmpeg the two halves overlap. On
1338
- // the fastest preset the one every ladder decision reads as the ceiling —
1339
- // that subtraction is most of the number being measured, so a small error in
1340
- // it becomes a large error in the answer.
1341
- //
1342
- // Raw frames remove all of it: no decoder, no scaler, nothing to subtract,
1343
- // and no dependence on the decode model. The cost is 25 MB of memory in a
1344
- // pipe for a few seconds.
1345
- const rawFramesPath = await decodeToRawFrames(ffmpegBin, log);
1346
- if (rawFramesPath === null) {
1347
- // Said once more, in the words that matter to whoever reads the log next:
1348
- // with no benchmark, `#sustainableHeights` filters nothing and every rung
1349
- // is offered, which is the failure of 2026-08-14 in full.
1350
- log.warn("hwaccel: the quality ladder is UNFILTERED on this host — nothing measured the encoder");
1351
- return [];
1352
- }
1353
- /** @type {Array<{ preset: string, pixelsPerSec: number }>} */
1354
- const results = [];
1355
- try {
1356
- for (const preset of BENCHMARK_PRESETS) {
1357
- const speed = await measureEncodeSlope(ffmpegBin, preset, rawFramesPath);
1358
- if (speed === null) {
1359
- log.warn(`hwaccel: preset benchmark "${preset}" produced no usable reading; skipping`);
1360
- continue;
1361
- }
1362
- const pixelsPerSec = BENCHMARK_REF_W * BENCHMARK_REF_H * TRANSCODE_FPS * speed;
1363
- results.push({ preset, pixelsPerSec });
1364
- log.info(
1365
- `hwaccel: preset "${preset}" ~= ${(pixelsPerSec / 1e6).toFixed(1)} Mpx/s ` +
1366
- `(${speed.toFixed(2)}x @ ${BENCHMARK_REF_W}x${BENCHMARK_REF_H}, real footage)`
1367
- );
1368
- }
1369
- } finally {
1370
- // The encoder was killed a moment ago and on Windows the handle outlives
1371
- // the signal, so removal is retried and its failure is not worth a session:
1372
- // this is a temp directory the operating system will clear anyway.
1373
- try {
1374
- rmSync(path.dirname(rawFramesPath), { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
1375
- } catch (error) {
1376
- log.warn(`hwaccel: could not remove the benchmark's raw frames: ${error instanceof Error ? error.message : String(error)}`);
1377
- }
1378
- }
1379
- return results;
1380
- }
1381
-
1382
- /**
1383
- * How fast one preset encodes, from ffmpeg's own reports of how much video it
1384
- * has written — not from the clock around the process.
1385
- *
1386
- * Timing whole runs measures the run STARTING. Measured 2026-08-15 on a desktop
1387
- * that spawns ffmpeg in ~0.4 s: three seconds of raw frames encoded that way
1388
- * put `fast` and `ultrafast` within 1.24x of each other, when libx264's own
1389
- * presets differ by several times the constant had swallowed the difference.
1390
- * The slope between two progress reports contains no part of the startup.
1391
- *
1392
- * The frames are written repeatedly so there is runway to measure over,
1393
- * whatever the preset's speed.
1394
- *
1395
- * @param {string} ffmpegBin
1396
- * @param {string} preset
1397
- * @param {string} rawFramesPath
1398
- * @returns {Promise<number | null>} Video seconds encoded per second of clock.
1399
- */
1400
- /**
1401
- * Video seconds produced per second of clock, from ffmpeg's own reports.
1402
- *
1403
- * Startup is excluded by taking a DIFFERENCE: it lands in the wall clock of
1404
- * every report equally, so it cancels between two of them. (The decode
1405
- * benchmark drops its first report instead, because there the first one is
1406
- * emitted at out_time zero; here reports with no time yet are discarded before
1407
- * they arrive, so the first kept one is already running.)
1408
- *
1409
- * @param {Array<{ wallSec: number, outSec: number }>} samples
1410
- * @param {number} [minimumWindowSec=ENCODE_BENCHMARK_WINDOW_SEC]
1411
- * @returns {number | null}
1412
- */
1413
- export function slopeOf(samples, minimumWindowSec = ENCODE_BENCHMARK_WINDOW_SEC) {
1414
- const first = samples[0];
1415
- const last = samples[samples.length - 1];
1416
- if (!first || !last || first === last) {
1417
- return null;
1418
- }
1419
- const took = last.wallSec - first.wallSec;
1420
- const produced = last.outSec - first.outSec;
1421
- if (!(took >= minimumWindowSec) || !(produced > 0)) {
1422
- return null;
1423
- }
1424
- const slope = produced / took;
1425
- // Nothing encodes a thousand times realtime. A figure above that is a
1426
- // measurement fault, and letting it through opens the whole ladder.
1427
- return slope <= ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED ? slope : null;
1428
- }
1429
-
1430
- function measureEncodeSlope(ffmpegBin, preset, rawFramesPath) {
1431
- return new Promise((resolve) => {
1432
- const args = [
1433
- "-hide_banner", "-loglevel", "error", "-nostats",
1434
- "-stream_loop", "-1",
1435
- "-f", "rawvideo", "-pix_fmt", "yuv420p",
1436
- "-s", `${BENCHMARK_REF_W}x${BENCHMARK_REF_H}`, "-r", String(TRANSCODE_FPS),
1437
- "-i", rawFramesPath,
1438
- "-c:v", "libx264", "-preset", preset, "-crf", SOFTWARE_CRF, "-pix_fmt", "yuv420p",
1439
- "-f", "null", "-",
1440
- "-progress", "pipe:1"
1441
- ];
1442
- /** @type {Array<{ wallSec: number, outSec: number }>} */
1443
- const samples = [];
1444
- let settled = false;
1445
- let buffered = "";
1446
- let child;
1447
- const startedAt = Date.now();
1448
- const finish = (value) => {
1449
- if (settled) {
1450
- return;
1451
- }
1452
- settled = true;
1453
- clearTimeout(timer);
1454
- try {
1455
- child?.kill("SIGKILL");
1456
- } catch {
1457
- // already gone
1458
- }
1459
- resolve(value);
1460
- };
1461
- const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
1462
- try {
1463
- child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1464
- } catch {
1465
- finish(null);
1466
- return;
1467
- }
1468
- // The frames come from a FILE, read on repeat by ffmpeg itself. Fed through
1469
- // a pipe instead, the fastest presets measured the pipe: `ultrafast` on a
1470
- // desktop wants raw frames at hundreds of megabytes a second, which no
1471
- // writer here can supply, and the reading then describes the feeding rather
1472
- // than the encoder.
1473
- child.stdout.on("data", (chunk) => {
1474
- buffered += String(chunk);
1475
- let newline = buffered.indexOf(NEWLINE);
1476
- while (newline >= 0) {
1477
- const line = buffered.slice(0, newline).trim();
1478
- buffered = buffered.slice(newline + 1);
1479
- if (line.startsWith("out_time_ms=")) {
1480
- const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
1481
- // `N/A` is not the only way ffmpeg says "no position yet": some builds
1482
- // print the smallest signed 64-bit integer, which IS finite and would
1483
- // be taken for a position nine trillion seconds before the start.
1484
- if (Number.isFinite(outSec) && outSec >= 0) {
1485
- samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
1486
- }
1487
- }
1488
- newline = buffered.indexOf(NEWLINE);
1489
- }
1490
- const slope = slopeOf(samples);
1491
- if (slope !== null) {
1492
- finish(slope);
1493
- }
1494
- });
1495
- child.on("error", () => finish(null));
1496
- // A preset that finished before the window was wide enough is measured from
1497
- // whatever it did report, provided two reports exist at all.
1498
- // A preset that finished before the wide window was covered is still
1499
- // measured — but never over a window of nothing. Two reports a millisecond
1500
- // apart would divide a frame of video by that millisecond and call the host
1501
- // twenty times faster than it is, and one such reading becomes the figure
1502
- // every ladder decision is taken from.
1503
- child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
1504
- });
1505
- }
1506
-
1507
- /**
1508
- * The benchmark's footage as raw frames: the calibration clip, looped to the
1509
- * benchmark's length and scaled to its size, decoded once.
1510
- *
1511
- * @param {string} ffmpegBin
1512
- * @param {{ info: (m: string) => void, warn: (m: string) => void }} log
1513
- * @returns {Promise<string | null>} Path to the raw frames, or null.
1514
- */
1515
- async function decodeToRawFrames(ffmpegBin, log) {
1516
- // A benchmark may leave a host unmeasured; it may never stop it from
1517
- // starting. Before this the temp directory was made outside any guard, so a
1518
- // read-only or missing TMPDIR rejected the promise that starts the proxy.
1519
- let directory;
1520
- try {
1521
- directory = mkdtempSync(path.join(os.tmpdir(), "torrent-tv-bench-"));
1522
- } catch (error) {
1523
- log.warn(
1524
- `hwaccel: no writable temp directory for the preset benchmark (${error instanceof Error ? error.message : String(error)}); ` +
1525
- "presets unmeasured, so no quality rung will be refused on this host"
1526
- );
1527
- return null;
1528
- }
1529
- const rawPath = path.join(directory, "frames.yuv");
1530
- const args = [
1531
- "-hide_banner", "-loglevel", "error",
1532
- "-stream_loop", "-1",
1533
- "-i", path.join(CALIBRATION_DIR, CALIBRATION_CLIPS[0]),
1534
- "-t", String(BENCHMARK_DURATION_SEC),
1535
- "-vf", `scale=${BENCHMARK_REF_W}:${BENCHMARK_REF_H},fps=${TRANSCODE_FPS}`,
1536
- "-an", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-y", rawPath
1537
- ];
1538
- const { code } = await runFfmpeg(ffmpegBin, args, 30000);
1539
- const expectedBytes = BENCHMARK_REF_W * BENCHMARK_REF_H * 1.5 * TRANSCODE_FPS * BENCHMARK_DURATION_SEC;
1540
- let written = 0;
1541
- try {
1542
- written = statSync(rawPath).size;
1543
- } catch {
1544
- written = 0;
1545
- }
1546
- if (code !== 0 || written < expectedBytes * 0.9) {
1547
- log.warn(
1548
- "hwaccel: could not decode the calibration clip for the preset benchmark " +
1549
- `(${written} of ~${Math.round(expectedBytes)} bytes); presets unmeasured, ` +
1550
- "so no quality rung will be refused on this host"
1551
- );
1552
- try {
1553
- rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
1554
- } catch {
1555
- // A temp directory the operating system will clear; not worth a start-up.
1556
- }
1557
- return null;
1558
- }
1559
- return rawPath;
1560
- }
1561
-
1562
- /**
1563
- * Pick the highest-quality (slowest) benchmarked preset that can encode
1564
- * `pixelsPerSecNeeded` with the speed margin. Falls back to the fastest
1565
- * benchmarked preset, or `"ultrafast"` when no benchmark is available.
1566
- *
1567
- * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
1568
- * @param {number} pixelsPerSecNeeded
1569
- * @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
1570
- * @returns {string}
1571
- */
1572
- /**
1573
- * What this host can do at its CHEAPEST preset — the ceiling of the ladder.
1574
- *
1575
- * Deliberately not the largest reading in the array. The list is in quality
1576
- * order, so its last measured entry is the cheapest preset; taking the maximum
1577
- * instead would let one noisy reading of an expensive preset raise the bar that
1578
- * decides which rungs are offered, and a rung offered on noise is a rung the
1579
- * host cannot hold. For choosing a preset the direction of that error is
1580
- * harmless; for deciding what to offer it is not, so the two use different
1581
- * statistics on purpose.
1582
- *
1583
- * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark
1584
- * @returns {number}
1585
- */
1586
- function cheapestPresetPixelsPerSec(benchmark) {
1587
- return benchmark[benchmark.length - 1]?.pixelsPerSec ?? 0;
1588
- }
1589
-
1590
- export function pickSoftwarePreset(benchmark, pixelsPerSecNeeded, cost = {}) {
1591
- if (!Array.isArray(benchmark) || benchmark.length === 0) {
1592
- return "ultrafast";
1593
- }
1594
- const observed = Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0
1595
- ? cost.observedDecodeCostSec
1596
- : null;
1597
- const bar = barFor(cost);
1598
- // The FIRST entry that clears the bar wins — the list is in quality order, so
1599
- // that is the best picture this host can hold. Every entry is examined rather
1600
- // than the walk stopping at the first miss, because the measurements do not
1601
- // always ascend with the list: on a busy machine on 2026-08-15 `faster` read
1602
- // below `fast` twice.
1603
- for (const entry of benchmark) {
1604
- const speed = predictedRealtimeSpeed({
1605
- decodeModel: cost.decodeModel ?? null,
1606
- encodePixelsPerSec: entry.pixelsPerSec,
1607
- outputPixelsPerSec: pixelsPerSecNeeded,
1608
- source: cost.source ?? null,
1609
- observedDecodeCostSec: observed
1610
- });
1611
- if (speed !== null && speed >= bar) {
1612
- return entry.preset;
1613
- }
1614
- }
1615
- // Nothing clears the bar: the cheapest preset, which is the last in quality
1616
- // order. Returning whichever preset measured fastest would hand an expensive
1617
- // one to a host that has just been shown to hold no rung at all.
1618
- return benchmark[benchmark.length - 1].preset;
1619
- }
1620
-
1621
- /**
1622
- * Whether a cost description can actually price decoding — a fit AND a source
1623
- * to apply it to. Without both, every prediction is encoder-only.
1624
- *
1625
- * @param {{ decodeModel?: object | null, source?: object | null }} cost
1626
- * @returns {boolean}
1627
- */
1628
- function isDecodePriced(cost) {
1629
- if (Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0) {
1630
- return true; // measured on the source itself, which needs no fit to stand on
1631
- }
1632
- return Boolean(cost?.decodeModel) && Boolean(cost?.source);
1633
- }
1634
-
1635
- // Resolution-ladder heights (output height rungs), high→low. The ladder is
1636
- // derived per-stream from the ceiling (the client-requested, source-capped
1637
- // output box): only rungs at or below the ceiling height are used, so the
1638
- // budget never upscales past what the client asked for. Standard heights keep
1639
- // the downscaled output at familiar resolutions.
1640
- const RESOLUTION_LADDER_HEIGHTS = [2160, 1440, 1080, 720, 540, 480, 360, 240];
1641
-
1642
- /**
1643
- * Build the resolution ladder for a ceiling box. Returns candidate output
1644
- * dimensions from the ceiling downward, preserving the ceiling's aspect ratio,
1645
- * each even-sized. The ceiling itself is always the top rung; ladder heights
1646
- * at or above it are skipped (never upscale). Deduped by height.
1647
- *
1648
- * @param {number} ceilingWidth
1649
- * @param {number} ceilingHeight
1650
- * @returns {Array<{ width: number, height: number }>} high→low
1651
- */
1652
- export function buildResolutionLadder(ceilingWidth, ceilingHeight) {
1653
- const cw = Number.isInteger(ceilingWidth) && ceilingWidth > 0 ? ceilingWidth : 0;
1654
- const ch = Number.isInteger(ceilingHeight) && ceilingHeight > 0 ? ceilingHeight : 0;
1655
- if (!cw || !ch) {
1656
- return [];
1657
- }
1658
- const even = (v) => {
1659
- const r = Math.round(v);
1660
- return Math.max(2, r - (r % 2));
1661
- };
1662
- /** @type {Array<{ width: number, height: number }>} */
1663
- const rungs = [{ width: cw, height: ch }];
1664
- for (const h of RESOLUTION_LADDER_HEIGHTS) {
1665
- if (h >= ch) {
1666
- continue; // at/above the ceiling — the ceiling rung already covers it
1667
- }
1668
- rungs.push({ width: even(cw * (h / ch)), height: h });
1669
- }
1670
- const seen = new Set();
1671
- return rungs.filter((rung) => {
1672
- if (seen.has(rung.height)) {
1673
- return false;
1674
- }
1675
- seen.add(rung.height);
1676
- return true;
1677
- });
1678
- }
1679
-
1680
- /**
1681
- * Choose the software encode settings (resolution + preset) that fit the
1682
- * realtime budget on this host. From the resolution ladder (ceiling downward),
1683
- * pick the HIGHEST rung whose encode throughput — predicted from the startup
1684
- * benchmark's fastest preset — clears the speed this file's own supply
1685
- * demands (`speedBar`). Then, at that resolution, pick the highest-quality
1686
- * preset that still clears it. When even the lowest rung cannot clear it, use the lowest rung with
1687
- * the fastest preset (best effort — a smaller picture beats sub-realtime
1688
- * playback at full size). Returns null when no benchmark or ceiling is
1689
- * available (the caller keeps the ceiling resolution and the default preset).
1690
- *
1691
- * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
1692
- * @param {{ width: number, height: number }} ceiling
1693
- * @param {number} outputFps
1694
- * @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
1695
- * @returns {{ width: number, height: number, preset: string, ladder: Array<{ width: number, height: number }>, rungIndex: number } | null}
1696
- */
1697
- export function chooseSoftwareEncodeSettings(benchmark, ceiling, outputFps, cost = {}) {
1698
- if (!Array.isArray(benchmark) || benchmark.length === 0) {
1699
- return null;
1700
- }
1701
- const fps = Number.isFinite(outputFps) && outputFps > 0 ? outputFps : TRANSCODE_FPS;
1702
- const ladder = buildResolutionLadder(ceiling?.width, ceiling?.height);
1703
- if (ladder.length === 0) {
1704
- return null;
1705
- }
1706
- const fastest = cheapestPresetPixelsPerSec(benchmark); // the cheapest preset's throughput
1707
- const bar = barFor(cost);
1708
- let chosenIndex = ladder.length - 1; // default: lowest rung (best effort)
1709
- for (let i = 0; i < ladder.length; i += 1) {
1710
- const speed = predictedRealtimeSpeed({
1711
- decodeModel: cost.decodeModel ?? null,
1712
- encodePixelsPerSec: fastest,
1713
- outputPixelsPerSec: ladder[i].width * ladder[i].height * fps,
1714
- source: cost.source ?? null
1715
- });
1716
- if (speed !== null && speed >= bar) {
1717
- chosenIndex = i;
1718
- break;
1719
- }
1720
- }
1721
- const chosen = ladder[chosenIndex];
1722
- const preset = pickSoftwarePreset(benchmark, chosen.width * chosen.height * fps, cost);
1723
- return { width: chosen.width, height: chosen.height, preset, ladder, rungIndex: chosenIndex };
1724
- }
1725
-
1726
- /**
1727
- * How fast this machine COPIES a picture, in seconds of film per second.
1728
- *
1729
- * The startup measurements price encoding and decoding, and a copied picture
1730
- * does neither: it reads packets and writes them out again. That left one whole
1731
- * branch of what this proxy does with no figure at all, and a figure is what
1732
- * every decision in the encoding layer is made from — where to put an encoder,
1733
- * how many to run, whether anybody will be left waiting. Without it a copied
1734
- * output was planned with no speed until its own run had been running long
1735
- * enough to report one, which is exactly the moment the plan matters most.
1736
- *
1737
- * Measured the same way as the others: ffmpeg's own progress, read as a slope
1738
- * over a window, so the process starting is outside the figure.
1739
- *
1740
- * The clip is joined to itself first rather than looped with `-stream_loop`.
1741
- * Looping charges a re-initialisation per lap measured on the addon host at
1742
- * 0.03 s for 480p and 0.12 s for 1080p and a copy of a five-second clip laps
1743
- * many times a second, so the reading would have been mostly re-initialisation.
1744
- *
1745
- * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} params
1746
- * @returns {Promise<number | null>} Seconds of film per second, or null where
1747
- * the reading could not be taken. Null means unmeasured and is never a
1748
- * substitute for a number.
1749
- */
1750
- export async function benchmarkCopySpeed({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
1751
- const log = logger ?? { info: () => {}, warn: () => {} };
1752
- const startedAt = Date.now();
1753
- // The largest clip in the set. A copy moves BYTES, so what it can do is a
1754
- // statement about the biggest pictures this host will be asked to pass
1755
- // through, and the small ones are covered by the same figure.
1756
- const clip = path.join(clipsDir, "cal-h264-1080-hi.mp4");
1757
- const speed = await measureCopySlope(ffmpegBin, clip);
1758
- if (!(speed > 0)) {
1759
- log.warn("hwaccel: copying could not be measured; a copied picture will be planned from its own run instead");
1760
- return null;
1761
- }
1762
- log.info(
1763
- `hwaccel: this host copies a picture at ${speed.toFixed(0)}x realtime ` +
1764
- `(measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
1765
- );
1766
- return speed;
1767
- }
1768
-
1769
- /**
1770
- * Seconds of film per second, copying one file, read from ffmpeg's progress.
1771
- *
1772
- * @param {string} ffmpegBin
1773
- * @param {string} filePath
1774
- * @returns {Promise<number | null>}
1775
- */
1776
- function measureCopySlope(ffmpegBin, filePath) {
1777
- return new Promise((resolve) => {
1778
- const args = [
1779
- "-hide_banner", "-loglevel", "error", "-nostats",
1780
- // Played over and over, because a copy gets through a five-second clip in
1781
- // milliseconds and a slope needs a window to be taken over. Looping
1782
- // charges the demuxer being re-opened once a lap, so what comes out is a
1783
- // FLOOR on what this host can copy — the safe direction, since a plan made
1784
- // from it expects copying to be slower than it is.
1785
- "-stream_loop", "-1", "-i", filePath,
1786
- // What a copied output does: packets in, packets out, nothing decoded and
1787
- // nothing encoded. Written nowhere, so the figure is this machine's own
1788
- // handling and not the disk under a temp directory.
1789
- "-c", "copy", "-f", "null", "-",
1790
- // Progress is reported every half second by default, which over a window
1791
- // of one second is two readings. This asks for twenty.
1792
- "-stats_period", "0.05",
1793
- "-progress", "pipe:1"
1794
- ];
1795
- /** @type {Array<{ wallSec: number, outSec: number }>} */
1796
- const samples = [];
1797
- let settled = false;
1798
- let buffered = "";
1799
- let child;
1800
- const startedAt = Date.now();
1801
- const finish = (value) => {
1802
- if (settled) {
1803
- return;
1804
- }
1805
- settled = true;
1806
- clearTimeout(timer);
1807
- try {
1808
- child?.kill("SIGKILL");
1809
- } catch {
1810
- // already gone
1811
- }
1812
- resolve(value);
1813
- };
1814
- const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
1815
- try {
1816
- child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1817
- } catch {
1818
- finish(null);
1819
- return;
1820
- }
1821
- child.stdout.on("data", (chunk) => {
1822
- buffered += String(chunk);
1823
- let newline = buffered.indexOf(NEWLINE);
1824
- while (newline >= 0) {
1825
- const line = buffered.slice(0, newline).trim();
1826
- buffered = buffered.slice(newline + 1);
1827
- if (line.startsWith("out_time_ms=")) {
1828
- const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
1829
- if (Number.isFinite(outSec) && outSec >= 0) {
1830
- samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
1831
- }
1832
- }
1833
- newline = buffered.indexOf(NEWLINE);
1834
- }
1835
- const slope = slopeOf(samples);
1836
- if (slope !== null) {
1837
- finish(slope);
1838
- }
1839
- });
1840
- child.on("error", () => finish(null));
1841
- child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
1842
- });
1843
- }
1
+ /**
2
+ * @file Hardware-accelerated H.264 encoder auto-detection.
3
+ *
4
+ * Probes the ffmpeg build and the host for a usable hardware H.264 encoder
5
+ * (NVENC / QSV / VAAPI / V4L2 M2M), verifying each candidate with a real
6
+ * test-encode before selecting it. Falls back to software libx264 when no
7
+ * hardware encoder is present or working.
8
+ *
9
+ * Deployment-agnostic: relies only on ffmpeg, the filesystem and
10
+ * `process.platform`; makes no assumptions about Home Assistant or any
11
+ * specific host. A garbled or unsupported hardware path simply fails its
12
+ * test-encode and is skipped, so the worst case is software encoding.
13
+ *
14
+ * A descriptor exposes:
15
+ * - `name` human-readable encoder id (e.g. "h264_vaapi")
16
+ * - `kind` "software" | "vaapi" | "qsv" | "nvenc" | "v4l2m2m"
17
+ * - `device` device node path or null
18
+ * - `inputArgs` ffmpeg args inserted before `-i` (decode/hwaccel setup)
19
+ * - `buildVideoArgs({ targetWidth, targetHeight, segmentDurationSec })`
20
+ * ffmpeg video filter + encoder args inserted after `-map`s
21
+ */
22
+
23
+ import { spawn } from "node:child_process";
24
+ import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
25
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
26
+ import os from "node:os";
27
+ import path from "node:path";
28
+ import { fitDecodeCost } from "./decode-cost-fit.js";
29
+ import { penaltiesFrom } from "./encode/contention.js";
30
+ import { fileURLToPath } from "node:url";
31
+ import {
32
+ parseFfmpegBitrateKbps,
33
+ parseFfmpegDurationSeconds,
34
+ parseFfmpegVideoDimensions,
35
+ parseFfmpegVideoFps
36
+ } from "./ffmpeg-banner.js";
37
+
38
+ import { keyFrameArgs, TRANSCODE_FPS } from "./encode/args.js";
39
+ // The five kinds, one class each. Detection and benchmarking stay in this file;
40
+ // how a kind is driven belongs to the kind.
41
+ import {
42
+ NvencEncoder,
43
+ QsvEncoder,
44
+ SoftwareEncoder,
45
+ V4l2m2mEncoder,
46
+ VaapiEncoder
47
+ } from "./encode/index.js";
48
+ // Re-exported so every caller goes on importing these figures from here:
49
+ // the same calculation, moved to sit beside the encoder kinds built from it.
50
+ export {
51
+ chooseOutputFps,
52
+ maxrateKbpsFor,
53
+ nominalKbpsForHeight,
54
+ nominalKbpsForMaxrate,
55
+ TRANSCODE_FPS
56
+ } from "./encode/args.js";
57
+
58
+ const BENCHMARK_REF_W = 640;
59
+ const BENCHMARK_REF_H = 360;
60
+ const BENCHMARK_DURATION_SEC = 3;
61
+ /**
62
+ * The narrowest window a slope may be taken over. Measured 2026-08-15: at a
63
+ * fifth of a second the readings were noisy enough to put `faster` and
64
+ * `veryfast` BELOW `fast`, which libx264 cannot do and `pickSoftwarePreset`
65
+ * walks the list assuming it ascends. Half a second was still noisy enough for that
66
+ * (measured again: veryfast below faster, twice), so a full second it is —
67
+ * about six seconds of startup for a ladder the whole budget then rests on.
68
+ */
69
+ const ENCODE_BENCHMARK_WINDOW_SEC = 1;
70
+ /** The narrowest window that may be used when a run ends early. */
71
+ const ENCODE_BENCHMARK_MIN_WINDOW_SEC = 0.2;
72
+ /** Above this a reading is a fault, not a fast machine. */
73
+ const ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED = 1000;
74
+ /**
75
+ * A preset that has not reported twice in this long is hung, not slow: reports
76
+ * arrive twice a second whatever the encoding speed.
77
+ */
78
+ const ENCODE_BENCHMARK_TIMEOUT_MS = 10_000;
79
+ /**
80
+ * How many times the calibration clip is joined to itself to measure copying.
81
+ *
82
+ * Not a figure about the machine: it is how much film the reading needs to have
83
+ * in front of it. A copy runs at hundreds of times realtime, and the slope is
84
+ * taken over a window of one second, so the input has to hold more film than the
85
+ * fastest plausible host gets through in that second. Forty laps of a five-second
86
+ * clip is 200 s of film, which covers the ceiling `slopeOf` will accept.
87
+ */
88
+ /** Progress reports arrive line by line. */
89
+ const NEWLINE = String.fromCharCode(10);
90
+ // Producing one second of video per second of clock. Not a margin and not a
91
+ // choice the definition of keeping up, and the bar when nothing better is
92
+ // known about the supply this step will meet.
93
+ const REALTIME = 1;
94
+ // The bar where decoding CANNOT be priced — no calibration fit, or a source the
95
+ // probe said too little about. This one is not measured and cannot be: the
96
+ // prediction it guards counts encoding only, which on the field host was
97
+ // several times optimistic, and there is no reading on such a host to correct
98
+ // it with. It is left at the figure it has had since before decoding was
99
+ // priced, because lowering it to realtime would make the least-measured hosts
100
+ // the most permissive. Where decoding IS priced, nothing chosen remains.
101
+ const UNPRICED_DECODE_BAR = 1.8;
102
+
103
+
104
+ // The five kinds live in `encode/`, one class each, and these keep the names
105
+ // every caller already uses. A kind states its own arguments and its own
106
+ // ladder of speed settings; detection and benchmarking stay here.
107
+ /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
108
+ export function softwareDescriptor() {
109
+ return new SoftwareEncoder();
110
+ }
111
+
112
+ /**
113
+ * @param {string} device
114
+ * @returns {import("./hwaccel.js").VideoEncoderDescriptor}
115
+ */
116
+ function vaapiDescriptor(device) {
117
+ return new VaapiEncoder(device);
118
+ }
119
+
120
+ /**
121
+ * @param {string} device
122
+ * @returns {import("./hwaccel.js").VideoEncoderDescriptor}
123
+ */
124
+ function qsvDescriptor(device) {
125
+ return new QsvEncoder(device);
126
+ }
127
+
128
+ /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
129
+ function nvencDescriptor() {
130
+ return new NvencEncoder();
131
+ }
132
+
133
+ /** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
134
+ function v4l2m2mDescriptor() {
135
+ return new V4l2m2mEncoder();
136
+ }
137
+
138
+
139
+
140
+ /**
141
+ * @typedef {Object} VideoEncoderDescriptor
142
+ * @property {string} name
143
+ * @property {"software"|"vaapi"|"qsv"|"nvenc"|"v4l2m2m"} kind
144
+ * @property {string|null} device
145
+ * @property {string[]} inputArgs
146
+ * @property {(opts: { targetWidth: number, targetHeight: number, segmentDurationSec: number, preset?: string, fps?: number, tonemap?: boolean, forcedKeyframeTimes?: number[] | null, nominalKbps?: number | null }) => string[]} buildVideoArgs
147
+ */
148
+
149
+ /**
150
+ * Run ffmpeg and resolve with its exit code and captured output.
151
+ *
152
+ * @param {string} ffmpegBin
153
+ * @param {string[]} args
154
+ * @param {number} [timeoutMs=12000]
155
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
156
+ */
157
+ function runFfmpeg(ffmpegBin, args, timeoutMs = 12000) {
158
+ return new Promise((resolve) => {
159
+ let stdout = "";
160
+ let stderr = "";
161
+ let settled = false;
162
+ let child;
163
+ const finish = (code) => {
164
+ if (settled) {
165
+ return;
166
+ }
167
+ settled = true;
168
+ resolve({ code, stdout, stderr });
169
+ };
170
+ try {
171
+ child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
172
+ } catch {
173
+ finish(-1);
174
+ return;
175
+ }
176
+ const timer = setTimeout(() => {
177
+ try {
178
+ child.kill("SIGKILL");
179
+ } catch {
180
+ // already gone
181
+ }
182
+ finish(-1);
183
+ }, timeoutMs);
184
+ child.stdout.on("data", (chunk) => {
185
+ stdout += String(chunk);
186
+ });
187
+ child.stderr.on("data", (d) => {
188
+ stderr += String(d);
189
+ });
190
+ child.on("error", () => {
191
+ clearTimeout(timer);
192
+ finish(-1);
193
+ });
194
+ child.on("exit", (code) => {
195
+ clearTimeout(timer);
196
+ finish(code ?? -1);
197
+ });
198
+ });
199
+ }
200
+
201
+ /** @returns {string[]} /dev/dri/renderD* nodes (VAAPI/QSV). */
202
+ function listRenderNodes() {
203
+ try {
204
+ return readdirSync("/dev/dri")
205
+ .filter((n) => n.startsWith("renderD"))
206
+ .map((n) => `/dev/dri/${n}`)
207
+ .sort();
208
+ } catch {
209
+ return [];
210
+ }
211
+ }
212
+
213
+ /** @returns {boolean} Whether any /dev/nvidia* node exists (NVENC). */
214
+ function hasNvidiaDevice() {
215
+ try {
216
+ return readdirSync("/dev").some((n) => /^nvidia(\d+)?$/.test(n));
217
+ } catch {
218
+ return false;
219
+ }
220
+ }
221
+
222
+ /** @returns {boolean} Whether any /dev/video* node exists (V4L2 M2M). */
223
+ function hasV4l2Device() {
224
+ try {
225
+ return readdirSync("/dev").some((n) => /^video\d+$/.test(n));
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Build a full ffmpeg command that encodes a short, *moving* synthetic clip
233
+ * (testsrc2 — far more representative than a static black frame) through the
234
+ * candidate encoder into real HLS segments in `outDir`, with keyframes forced
235
+ * on segment boundaries. Verifying the resulting segments (see
236
+ * {@link verifySegmentsDecodeCleanly}) catches encoders that silently produce
237
+ * a corrupted or non-IDR-aligned stream (e.g. some V4L2 M2M builds).
238
+ *
239
+ * @param {VideoEncoderDescriptor} descriptor
240
+ * @param {number} segmentDurationSec
241
+ * @param {string} outDir
242
+ * @returns {string[]}
243
+ */
244
+ function buildEncoderTestArgs(descriptor, segmentDurationSec, outDir) {
245
+ const durationSec = Math.max(8, segmentDurationSec * 3);
246
+ const source = ["-f", "lavfi", "-i", `testsrc2=s=640x360:r=${TRANSCODE_FPS}:d=${durationSec}`];
247
+ const kf = keyFrameArgs(segmentDurationSec);
248
+
249
+ /** @type {string[]} */
250
+ let pre = ["-hide_banner", "-loglevel", "error"];
251
+ /** @type {string[]} */
252
+ let encode;
253
+ switch (descriptor.kind) {
254
+ case "vaapi":
255
+ pre = [...pre, "-vaapi_device", String(descriptor.device)];
256
+ encode = ["-vf", "format=nv12,hwupload", "-c:v", "h264_vaapi", "-qp", "24", ...kf];
257
+ break;
258
+ case "qsv":
259
+ pre = [...pre, "-qsv_device", String(descriptor.device)];
260
+ encode = ["-vf", "hwupload=extra_hw_frames=16,format=qsv", "-c:v", "h264_qsv", "-global_quality", "24", ...kf];
261
+ break;
262
+ case "nvenc":
263
+ encode = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", "24", "-pix_fmt", "yuv420p", ...kf];
264
+ break;
265
+ case "v4l2m2m":
266
+ encode = ["-pix_fmt", "yuv420p", "-c:v", "h264_v4l2m2m", "-num_capture_buffers", "32", "-b:v", "3M", "-g", String(TRANSCODE_FPS * segmentDurationSec), ...kf];
267
+ break;
268
+ default:
269
+ encode = ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", ...kf];
270
+ break;
271
+ }
272
+
273
+ const hlsOut = [
274
+ "-f", "hls",
275
+ "-hls_time", String(segmentDurationSec),
276
+ "-hls_list_size", "0",
277
+ "-hls_flags", "independent_segments",
278
+ // fMP4 (CMAF) — matches the runtime pipeline (hls-session-manager).
279
+ "-hls_segment_type", "fmp4",
280
+ "-hls_fmp4_init_filename", "init.mp4",
281
+ "-hls_segment_filename", path.join(outDir, "seg-%03d.m4s"),
282
+ path.join(outDir, "index.m3u8")
283
+ ];
284
+ return [...pre, ...source, ...encode, ...hlsOut];
285
+ }
286
+
287
+ /**
288
+ * Verify the HLS segments produced by the test encode are valid: at least two
289
+ * segments exist, and each decodes standalone without errors. A segment that
290
+ * does not begin with a keyframe (broken/corrupted output) emits decode errors
291
+ * when read on its own, which fails this check.
292
+ *
293
+ * @param {string} ffmpegBin
294
+ * @param {string} outDir
295
+ * @returns {Promise<boolean>}
296
+ */
297
+ async function verifySegmentsDecodeCleanly(ffmpegBin, outDir) {
298
+ let files;
299
+ try {
300
+ files = readdirSync(outDir).filter((n) => /^seg-\d+\.m4s$/.test(n));
301
+ } catch {
302
+ return false;
303
+ }
304
+ if (files.length < 2) {
305
+ return false;
306
+ }
307
+ // fMP4: parameter sets (SPS/PPS) live in init.mp4, not in each segment.
308
+ // Decode the whole playlist (ffmpeg's own, which references init.mp4 via
309
+ // #EXT-X-MAP), so every segment is exercised together with the init. Any
310
+ // corrupt / non-conformant segment (e.g. some V4L2 M2M builds emit a stray
311
+ // no-picture access unit) surfaces as a decode error here.
312
+ const result = await runFfmpeg(
313
+ ffmpegBin,
314
+ ["-hide_banner", "-loglevel", "error", "-i", path.join(outDir, "index.m3u8"), "-f", "null", "-"],
315
+ 12000
316
+ );
317
+ return result.code === 0 && result.stderr.trim().length === 0;
318
+ }
319
+
320
+ /**
321
+ * Detect the best usable H.264 encoder. Always resolves (falls back to
322
+ * software libx264). Each hardware candidate is verified with a real
323
+ * test-encode before being selected.
324
+ *
325
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, segmentDurationSec?: number }} options
326
+ * @returns {Promise<VideoEncoderDescriptor>}
327
+ */
328
+ export async function detectVideoEncoder({ ffmpegBin, logger, segmentDurationSec = 4 }) {
329
+ const log = logger ?? { info: () => {}, warn: () => {} };
330
+ const software = softwareDescriptor();
331
+
332
+ const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-encoders"], 10000);
333
+ if (code !== 0) {
334
+ log.warn("hwaccel: could not list ffmpeg encoders; using software libx264");
335
+ return software;
336
+ }
337
+ const has = (name) => stdout.includes(name);
338
+
339
+ /** @type {VideoEncoderDescriptor[]} */
340
+ const candidates = [];
341
+ const renderNodes = listRenderNodes();
342
+ if (has("h264_nvenc") && hasNvidiaDevice()) {
343
+ candidates.push(nvencDescriptor());
344
+ }
345
+ if (has("h264_qsv") && renderNodes.length > 0) {
346
+ candidates.push(qsvDescriptor(renderNodes[0]));
347
+ }
348
+ if (has("h264_vaapi") && renderNodes.length > 0) {
349
+ candidates.push(vaapiDescriptor(renderNodes[0]));
350
+ }
351
+ // h264_v4l2m2m (ARM SoC / Raspberry Pi / HA Yellow). It is gated behind the
352
+ // strict keyframe-alignment test below, because some V4L2 M2M builds silently
353
+ // emit a corrupted / non-IDR-aligned stream; the test rejects those and the
354
+ // host falls back to software libx264.
355
+ if (has("h264_v4l2m2m") && hasV4l2Device()) {
356
+ candidates.push(v4l2m2mDescriptor());
357
+ }
358
+
359
+ for (const candidate of candidates) {
360
+ const dir = mkdtempSync(path.join(os.tmpdir(), "tt-hwtest-"));
361
+ let ok = false;
362
+ try {
363
+ const encoded = await runFfmpeg(
364
+ ffmpegBin,
365
+ buildEncoderTestArgs(candidate, segmentDurationSec, dir),
366
+ 25000
367
+ );
368
+ if (encoded.code === 0) {
369
+ ok = await verifySegmentsDecodeCleanly(ffmpegBin, dir);
370
+ }
371
+ } finally {
372
+ try {
373
+ rmSync(dir, { recursive: true, force: true });
374
+ } catch {
375
+ // best effort
376
+ }
377
+ }
378
+ if (ok) {
379
+ log.info(
380
+ `hwaccel: using hardware encoder ${candidate.name}` +
381
+ `${candidate.device ? ` (${candidate.device})` : ""}`
382
+ );
383
+ return candidate;
384
+ }
385
+ log.warn(`hwaccel: ${candidate.name} failed the HLS keyframe-alignment test; skipping`);
386
+ }
387
+
388
+ log.info("hwaccel: no working hardware encoder; using software libx264");
389
+ return software;
390
+ }
391
+
392
+ /**
393
+ * Detect whether this ffmpeg build has the filters needed for the HDR→SDR
394
+ * tone-map chain (`zscale`, from libzimg, and `tonemap`). Both are required;
395
+ * when either is missing, HDR sources are re-encoded without tone mapping
396
+ * (washed-out but playable). Always resolves.
397
+ *
398
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
399
+ * @returns {Promise<boolean>}
400
+ */
401
+ export async function detectTonemapSupport({ ffmpegBin, logger }) {
402
+ const log = logger ?? { info: () => {}, warn: () => {} };
403
+ const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-filters"], 10000);
404
+ if (code !== 0) {
405
+ log.warn("hwaccel: could not list ffmpeg filters; HDR tone mapping disabled");
406
+ return false;
407
+ }
408
+ // `-filters` prints one filter per line: "... zscale ...", "... tonemap ...".
409
+ const hasZscale = /\bzscale\b/.test(stdout);
410
+ const hasTonemap = /\btonemap\b/.test(stdout);
411
+ const supported = hasZscale && hasTonemap;
412
+ log.info(
413
+ `hwaccel: HDR tone mapping ${supported ? "available" : "unavailable"} ` +
414
+ `(zscale=${hasZscale} tonemap=${hasTonemap})`
415
+ );
416
+ return supported;
417
+ }
418
+
419
+
420
+ // The clips the decode cost is fitted from. They ship with the package
421
+ // (`assets/calibration/`), cut from Netflix Open Content "Meridian" (CC-BY 4.0)
422
+ // real, grainy live action, because a generated `testsrc2` clip decodes 158 %
423
+ // away from a real film where these are 11 % away (measured 2026-08-14).
424
+ //
425
+ // Three sizes at two bitrates each, with the axes varied INDEPENDENTLY. The set
426
+ // this replaced was three clips for three unknowns, two of them at the same
427
+ // size: an exact system, which cannot fail visibly. On 2026-08-17 it returned
428
+ // `0.007542 × Mpx/s + 0.000000 × Mbit/s + 0.0000 s/s` the bitrate term and
429
+ // the constant exactly zero and the prediction on top of it was 1.8-2.2x
430
+ // optimistic. Six points leave three spare, so the fit has a residual, and a
431
+ // term the data does not determine can be refused instead of published as a
432
+ // zero that looks measured. See `assets/calibration/NOTICE.md`.
433
+ //
434
+ // One set PER CODEC FAMILY, because a family is what the model describes. The
435
+ // fit used to be H.264 only, while a video that has to be RE-ENCODED is by
436
+ // definition one the browser could not play which is to say HEVC, 10-bit or
437
+ // AV1 and those decode dearer per pixel on the same box. Pricing them with
438
+ // H.264 constants is the one case the model is always asked about and was never
439
+ // measured on.
440
+ //
441
+ // A family that has no set of its own is priced with H.264's, which is what
442
+ // happened to every family before this; the line says so rather than implying
443
+ // it. AV1 has no set yet: the survey of 2026-07-10 found it rare where HEVC was
444
+ // 18 % of releases, so it waits for the same treatment.
445
+ const CALIBRATION_SETS = {
446
+ h264: [
447
+ "cal-h264-1080-hi.mp4",
448
+ "cal-h264-1080-lo.mp4",
449
+ "cal-h264-720-hi.mp4",
450
+ "cal-h264-720-lo.mp4",
451
+ "cal-h264-480-hi.mp4",
452
+ "cal-h264-480-lo.mp4"
453
+ ],
454
+ hevc: [
455
+ "cal-hevc-1080-hi.mp4",
456
+ "cal-hevc-1080-lo.mp4",
457
+ "cal-hevc-480-hi.mp4",
458
+ "cal-hevc-480-lo.mp4"
459
+ ],
460
+ hevc10: [
461
+ "cal-hevc10-1080-hi.mp4",
462
+ "cal-hevc10-1080-lo.mp4",
463
+ "cal-hevc10-480-hi.mp4",
464
+ "cal-hevc10-480-lo.mp4"
465
+ ]
466
+ };
467
+ const CALIBRATION_CLIPS = CALIBRATION_SETS.h264;
468
+ const CALIBRATION_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "calibration");
469
+ // How wide the measured window must be before the slope is trusted, and how
470
+ // long to wait for it at most.
471
+ //
472
+ // Half a second, and it is the TIMING noise that sets it rather than the amount
473
+ // of video: the slope is output time against wall time, both read from the same
474
+ // two progress lines, and the jitter in stamping one is milliseconds so half
475
+ // a second of window is a fraction of a percent of error on any host. What used
476
+ // to make a longer window necessary was the clip restarting inside it, and that
477
+ // is gone: the stream is continuous now. Measured 2026-08-22 against the
478
+ // continuous-pass truth on a desktop: -3.0 % and +0.6 % at half a second, with
479
+ // the readings spread 2-6 %, against -25 % and -33 % for the loop it replaces.
480
+ // Half a second also costs the startup about 0.6 s per clip less, which matters
481
+ // because every clip of every codec family is paid for before any viewer
482
+ // exists.
483
+ const DECODE_WINDOW_MIN_SEC = 0.5;
484
+ const DECODE_WINDOW_MAX_MS = 8000;
485
+
486
+ /**
487
+ * Read what a calibration clip IS from the decode run's own output: the
488
+ * dimensions, the frame rate and the bitrate ffmpeg reports for it. Read rather
489
+ * than declared, so replacing a clip cannot silently invalidate the fit.
490
+ *
491
+ * @param {string} stderr
492
+ * @returns {{ megapixelsPerSecond: number, megabitsPerSecond: number, durationSeconds: number } | null}
493
+ */
494
+ function parseClipCharacteristics(stderr) {
495
+ // The same readers the session manager uses on the same banner — one parser
496
+ // per fact, so a second copy cannot drift from the first.
497
+ const { width, height } = parseFfmpegVideoDimensions(stderr);
498
+ const rate = parseFfmpegVideoFps(stderr);
499
+ const seconds = parseFfmpegDurationSeconds(stderr);
500
+ const kbps = parseFfmpegBitrateKbps(stderr);
501
+ if (!(width > 0) || !(height > 0) || !(rate > 0) || !(seconds > 0) || !(kbps > 0)) {
502
+ return null;
503
+ }
504
+ return {
505
+ megapixelsPerSecond: (width * height * rate) / 1e6,
506
+ megabitsPerSecond: kbps / 1000,
507
+ durationSeconds: seconds
508
+ };
509
+ }
510
+
511
+ /**
512
+ * Measure what DECODING costs on this host, as seconds of work per second of
513
+ * video, and solve it into three host constants:
514
+ *
515
+ * decodeCost = a × Mpixel/s + b × Mbit/s + c
516
+ *
517
+ * Why it exists: the preset benchmark below measures ENCODING only, and a
518
+ * re-encode pays for both halves. Measured 2026-08-14 on the addon host, that
519
+ * omission made the budget offer a 240p rung it then ran at 0.39-0.95× — the
520
+ * benchmark said the host cleared the bar 2. over. With the decode term the
521
+ * same file predicts within 4.8 %; without it the error on that rung was 209 %.
522
+ *
523
+ * The constants are properties of the HOST, so this runs once at startup (about
524
+ * 5 s on a CM4) and any source is then priced from figures the probe already
525
+ * has nothing is added to a session's cold start.
526
+ *
527
+ * They are also properties of the CODEC, and the clips are H.264: HEVC, AV1 and
528
+ * 10-bit decode dearer per pixel on the same machine, and a source that has to
529
+ * be re-encoded is by definition one this browser could not play, which is
530
+ * usually not H.264. So the fit is optimistic exactly there. Closing that needs
531
+ * clips in those codecs, and is its own roadmap item.
532
+ *
533
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} options
534
+ * @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
535
+ */
536
+ /**
537
+ * What a second job costs on this host, measured rather than assumed.
538
+ *
539
+ * The budget adds seconds of work per second of content this encode, plus
540
+ * that decode, plus what is already committed — and the addon host contradicted
541
+ * that directly on 2026-08-18: decoding ran at 2.10-2.25x alone, 0.79-0.90x
542
+ * with one encoder beside it and 0.56-0.64x with two. The same work costs 2.6×
543
+ * more for having company. Heat is not the cause (the hot idle machine was the
544
+ * fastest reading of all); four cores sharing one path to memory is.
545
+ *
546
+ * So it is measured the way everything else here is: the same clip decoded
547
+ * alone, then decoded again while an encoder of the same clip runs beside it.
548
+ * The ratio is the penalty. The encoder is stopped as soon as the reading is
549
+ * taken, and the whole thing costs one decode plus one short encode.
550
+ *
551
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string, upTo?: number }} options
552
+ * @returns {Promise<Map<number, number> | null>} Penalties by how many other
553
+ * jobs were running, or null when the readings could not be taken.
554
+ */
555
+ export async function benchmarkContention({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR, upTo = 2 }) {
556
+ const log = logger ?? { info: () => {}, warn: () => {} };
557
+ // The cheapest clip in the set: this measures the MACHINE's behaviour under
558
+ // company, not the clip's own cost, so the smallest one says it soonest.
559
+ const clip = path.join(clipsDir, "cal-h264-480-lo.mp4");
560
+ const startedAt = Date.now();
561
+ // Lifted once and decoded three times from the same bytes. Going through
562
+ // `measureDecodeSlope` lifted it again for every reading — three process
563
+ // starts on a path that is awaited before the proxy's tunnel opens, for a
564
+ // remux whose result had not changed.
565
+ const streams = await extractFamilyStreams(ffmpegBin, [clip], "h264");
566
+ const stream = streams?.[0];
567
+ if (!stream) {
568
+ log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
569
+ return null;
570
+ }
571
+ const alone = await decodePipedStream(ffmpegBin, stream, log);
572
+ if (!alone?.speed) {
573
+ log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
574
+ return null;
575
+ }
576
+ /** @type {Array<{ others: number, speed: number }>} */
577
+ const beside = [];
578
+ /** @type {import("node:child_process").ChildProcess[]} */
579
+ const load = [];
580
+ try {
581
+ for (let others = 1; others <= Math.max(1, upTo); others += 1) {
582
+ load.push(
583
+ spawn(
584
+ ffmpegBin,
585
+ [
586
+ "-hide_banner", "-loglevel", "error", "-nostats",
587
+ "-stream_loop", "-1", "-i", clip,
588
+ "-an", "-c:v", "libx264", "-preset", "fast", "-f", "null", "-"
589
+ ],
590
+ { stdio: ["ignore", "ignore", "ignore"], windowsHide: true }
591
+ )
592
+ );
593
+ // Let the encoder reach its own speed before reading anything: an encode
594
+ // measured in its first moments is measuring the process starting.
595
+ await new Promise((resolve) => {
596
+ setTimeout(resolve, 2_000);
597
+ });
598
+ const withCompany = await decodePipedStream(ffmpegBin, stream, log);
599
+ if (withCompany?.speed) {
600
+ beside.push({ others, speed: withCompany.speed });
601
+ }
602
+ }
603
+ } finally {
604
+ for (const child of load) {
605
+ try {
606
+ child.kill("SIGKILL");
607
+ } catch {
608
+ // Already gone: the reading is what mattered, and nothing else uses it.
609
+ }
610
+ }
611
+ }
612
+ const penalties = penaltiesFrom(alone.speed, beside);
613
+ if (!penalties) {
614
+ log.warn("hwaccel: contention readings said nothing; costs will be added as though jobs were independent");
615
+ return null;
616
+ }
617
+ log.info(
618
+ `hwaccel: a second job costs ${[...penalties.entries()]
619
+ .map(([others, penalty]) => `${penalty.toFixed(2)}x beside ${others}`)
620
+ .join(", ")} ` +
621
+ `(decode alone ${alone.speed.toFixed(2)}x, ` +
622
+ `${beside.map((reading) => `${reading.speed.toFixed(2)}x beside ${reading.others}`).join(", ")}, ` +
623
+ `measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
624
+ );
625
+ return penalties;
626
+ }
627
+
628
+ export async function benchmarkDecodeCost({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
629
+ const log = logger ?? { info: () => {}, warn: () => {} };
630
+ const startedAllAt = Date.now();
631
+ /** @type {Record<string, { pixelTerm: number, bitrateTerm: number, constantTerm: number }>} */
632
+ const families = {};
633
+ for (const [family, clips] of Object.entries(CALIBRATION_SETS)) {
634
+ const fitted = await fitOneFamily({ ffmpegBin, log, clipsDir, family, clips });
635
+ if (fitted) {
636
+ families[family] = fitted;
637
+ }
638
+ }
639
+ if (!families.h264) {
640
+ // H.264 is the family every other one falls back to, so without it there is
641
+ // no model at all rather than a partial one. Which families DID fit is said
642
+ // anyway: on a fast host the H.264 clips decode at 20-80x and the readings
643
+ // stop being ordered measured 2026-08-20 on a desktop, 1080p at 9.35
644
+ // Mbit/s costing 0.0307 s/s against 720p at 9.94 costing 0.0472, which is
645
+ // not a thing a decoder does so a failure here is a measurement problem
646
+ // and not a missing file, and the line has to let those be told apart.
647
+ log.warn(
648
+ "hwaccel: decode cost unknown the H.264 clips did not fit" +
649
+ (Object.keys(families).length > 0
650
+ ? `, though ${Object.keys(families).join(" and ")} did`
651
+ : "")
652
+ );
653
+ return null;
654
+ }
655
+ const missing = Object.keys(CALIBRATION_SETS).filter((family) => !families[family]);
656
+ log.info(
657
+ `hwaccel: decode cost measured for ${Object.keys(families).join(", ")}` +
658
+ (missing.length > 0 ? `; ${missing.join(" and ")} priced as H.264` : "") +
659
+ ` (in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
660
+ );
661
+ return { families, ...families.h264 };
662
+ }
663
+
664
+ /**
665
+ * Fit one codec family's decode cost from its own clips.
666
+ *
667
+ * @param {{ ffmpegBin: string, log: { info: Function, warn: Function }, clipsDir: string, family: string, clips: string[] }} params
668
+ * @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
669
+ */
670
+ async function fitOneFamily({ ffmpegBin, log, clipsDir, family, clips }) {
671
+ const startedAllAt = Date.now();
672
+ /** @type {Array<{ megapixelsPerSecond: number, megabitsPerSecond: number, costSecondsPerSecond: number }>} */
673
+ const samples = [];
674
+ // Every clip of the family is lifted out of its container FIRST, in one
675
+ // ffmpeg run. See `extractFamilyStreams` for why one run rather than one per
676
+ // clip, and why before the measurements rather than beside them.
677
+ const streams = await extractFamilyStreams(
678
+ ffmpegBin,
679
+ clips.map((clip) => path.join(clipsDir, clip)),
680
+ family
681
+ );
682
+ if (!streams) {
683
+ log.warn(
684
+ `hwaccel: ${family} cannot be lifted out of its container — no Annex-B filter is mapped for it, ` +
685
+ `so its clips were never measured`
686
+ );
687
+ return null;
688
+ }
689
+ for (const [index, clip] of clips.entries()) {
690
+ const stream = streams[index];
691
+ const measured = stream ? await decodePipedStream(ffmpegBin, stream, log) : null;
692
+ if (!measured?.speed) {
693
+ log.warn(
694
+ `hwaccel: decode benchmark "${clip}" said nothing; ${family} not measured` +
695
+ (measured?.error ? ` — ${measured.error}` : " — the clip could not be lifted out of its container")
696
+ );
697
+ return null;
698
+ }
699
+ const cost = 1 / measured.speed;
700
+ samples.push({
701
+ megapixelsPerSecond: measured.megapixelsPerSecond,
702
+ megabitsPerSecond: measured.megabitsPerSecond,
703
+ costSecondsPerSecond: cost
704
+ });
705
+ log.info(
706
+ `hwaccel: decode "${clip}" ${measured.megapixelsPerSecond.toFixed(1)} Mpx/s ` +
707
+ `${measured.megabitsPerSecond.toFixed(2)} Mbit/s -> ${measured.speed.toFixed(1)}x ` +
708
+ `(cost ${cost.toFixed(4)} s/s, over ${measured.windowSec.toFixed(1)}s of decoding)`
709
+ );
710
+ }
711
+ const fitted = fitDecodeCost(samples);
712
+ if (!fitted) {
713
+ log.warn(`hwaccel: ${family} decode cost could not be fitted to these measurements`);
714
+ return null;
715
+ }
716
+ log.info(
717
+ `hwaccel: ${family} decode cost = ${fitted.pixelTerm.toFixed(6)} × Mpx/s + ${fitted.bitrateTerm.toFixed(6)} × Mbit/s ` +
718
+ `+ ${fitted.constantTerm.toFixed(4)} s/s (${fitted.shape} from ${fitted.samples} clips, ` +
719
+ `typical disagreement ${fitted.residualRms.toFixed(4)} s/s` +
720
+ // Named rather than implied: a zero in the line above means "not
721
+ // measured" for a dropped term and "measured to be nothing" otherwise,
722
+ // and those are different claims.
723
+ (fitted.dropped.length > 0 ? `, ${fitted.dropped.join(" and ")} not determined by these clips` : "") +
724
+ `, measured in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
725
+ );
726
+ return { pixelTerm: fitted.pixelTerm, bitrateTerm: fitted.bitrateTerm, constantTerm: fitted.constantTerm };
727
+ }
728
+
729
+ /**
730
+ * The bitstream filter and demuxer that turn a clip's video track into a
731
+ * continuous elementary stream, by codec family.
732
+ *
733
+ * H.264 and HEVC in MP4 keep their parameter sets in the container's `avcC` /
734
+ * `hvcC` and their access units length-prefixed; Annex-B carries them inline,
735
+ * with start codes, which is what makes plain byte concatenation a valid
736
+ * stream. That is the property this whole measurement rests on.
737
+ */
738
+ const ANNEX_B_BY_FAMILY = {
739
+ h264: { filter: "h264_mp4toannexb", demuxer: "h264" },
740
+ hevc: { filter: "hevc_mp4toannexb", demuxer: "hevc" },
741
+ hevc10: { filter: "hevc_mp4toannexb", demuxer: "hevc" }
742
+ };
743
+
744
+ /**
745
+ * The last complaint in an ffmpeg stderr, for a line that has to say why.
746
+ *
747
+ * @param {string} stderr
748
+ * @returns {string}
749
+ */
750
+ function lastErrorLine(stderr) {
751
+ const lines = String(stderr ?? "")
752
+ .split(/\r?\n/)
753
+ .map((line) => line.trim())
754
+ .filter((line) => line.length > 0);
755
+ return lines[lines.length - 1] ?? "";
756
+ }
757
+
758
+ /**
759
+ * How long the lift may take before it is abandoned. It is a remux of a few
760
+ * megabytes, so this is not a budget — it is the difference between a startup
761
+ * that reports a failure and one that never finishes. Every other ffmpeg run in
762
+ * this file has such a bound; this one did not, and it is awaited before the
763
+ * proxy's tunnel opens.
764
+ */
765
+ const EXTRACT_TIMEOUT_MS = 20_000;
766
+
767
+ /**
768
+ * Lift a whole family's clips out of their containers, as Annex-B elementary
769
+ * streams, in ONE ffmpeg run.
770
+ *
771
+ * No re-encoding the frames are copied — so the work itself is trivial and
772
+ * the cost is almost entirely the process. Doing one process per clip added
773
+ * 11 s to the startup here (fourteen clips at about 0.83 s each), and running
774
+ * them concurrently did not help: six at once took 4.75 s against 0.89 s for
775
+ * one, so the machine serialises them. One run with many inputs and many
776
+ * outputs costs one process.
777
+ *
778
+ * The outputs go to temporary files because several outputs cannot share one
779
+ * pipe; they are read into memory and deleted immediately, and nothing about
780
+ * this measurement is kept between runs.
781
+ *
782
+ * Before the measurements, never beside them: a remux running next to a decode
783
+ * is a second job on the machine, and this benchmark exists to find out what
784
+ * ONE job costs here.
785
+ *
786
+ * @param {string} ffmpegBin
787
+ * @param {string[]} clipPaths
788
+ * @param {string} family
789
+ * @returns {Promise<Array<{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number } | null> | null>}
790
+ * One entry per clip, in order; null when the family cannot be lifted at all.
791
+ */
792
+ async function extractFamilyStreams(ffmpegBin, clipPaths, family) {
793
+ const shape = ANNEX_B_BY_FAMILY[family];
794
+ // A family with no mapping is a hard failure, not a silent fallback to
795
+ // H.264's filter. AV1 has no Annex-B form at all (its packaging is OBU), and
796
+ // MPEG-2 and VC-1 have no `*_mp4toannexb` filter so the three families the
797
+ // roadmap plans next cannot come through here, and finding that out as
798
+ // "the clip failed" would send the reader after the clip.
799
+ if (!shape) {
800
+ return null;
801
+ }
802
+ const workDir = await mkdtemp(path.join(os.tmpdir(), "ttv-calibration-"));
803
+ const outputs = clipPaths.map((_, index) => path.join(workDir, `stream-${index}.${shape.demuxer}`));
804
+ /** @type {string[]} */
805
+ const args = ["-hide_banner", "-loglevel", "info", "-nostats", "-y"];
806
+ for (const clipPath of clipPaths) {
807
+ args.push("-i", clipPath);
808
+ }
809
+ for (const [index, output] of outputs.entries()) {
810
+ args.push("-map", `${index}:v:0`, "-c:v", "copy", "-bsf:v", shape.filter, "-f", shape.demuxer, output);
811
+ }
812
+ const stderr = await runCapturingStderr(ffmpegBin, args, EXTRACT_TIMEOUT_MS);
813
+ try {
814
+ if (stderr === null) {
815
+ return null;
816
+ }
817
+ // One banner block per input, in the order they were given. Read rather
818
+ // than declared, so replacing a clip cannot silently invalidate the fit
819
+ // that rests on it.
820
+ const blocks = splitInputBlocks(stderr, clipPaths.length);
821
+ return await Promise.all(clipPaths.map(async (_, index) => {
822
+ const block = blocks[index];
823
+ if (!block) {
824
+ return null;
825
+ }
826
+ const clipInfo = parseClipCharacteristics(block);
827
+ const fps = parseFfmpegVideoFps(block);
828
+ if (!clipInfo || !(fps > 0)) {
829
+ return null;
830
+ }
831
+ let bytes;
832
+ try {
833
+ bytes = await readFile(outputs[index]);
834
+ } catch {
835
+ return null;
836
+ }
837
+ if (bytes.length === 0) {
838
+ return null;
839
+ }
840
+ return {
841
+ bytes,
842
+ demuxer: shape.demuxer,
843
+ megapixelsPerSecond: clipInfo.megapixelsPerSecond,
844
+ megabitsPerSecond: clipInfo.megabitsPerSecond,
845
+ fps
846
+ };
847
+ }));
848
+ } finally {
849
+ await rm(workDir, { recursive: true, force: true }).catch(() => {});
850
+ }
851
+ }
852
+
853
+ /**
854
+ * The part of an ffmpeg banner describing each input, in order.
855
+ *
856
+ * ffmpeg prints one `Input #N, …` block per input and then the stream mapping;
857
+ * the parsers here read a single input's facts, so they are given a single
858
+ * input's text rather than the whole banner.
859
+ *
860
+ * @param {string} stderr
861
+ * @param {number} count
862
+ * @returns {string[]}
863
+ */
864
+ function splitInputBlocks(stderr, count) {
865
+ /** @type {string[]} */
866
+ const blocks = [];
867
+ for (let index = 0; index < count; index += 1) {
868
+ const from = stderr.indexOf(`Input #${index},`);
869
+ if (from < 0) {
870
+ blocks.push("");
871
+ continue;
872
+ }
873
+ const nextInput = stderr.indexOf(`Input #${index + 1},`, from);
874
+ const mapping = stderr.indexOf("Stream mapping:", from);
875
+ const ends = [nextInput, mapping].filter((at) => at > from);
876
+ blocks.push(stderr.slice(from, ends.length > 0 ? Math.min(...ends) : stderr.length));
877
+ }
878
+ return blocks;
879
+ }
880
+
881
+ /**
882
+ * Run ffmpeg to completion and return its stderr, or null when it failed or
883
+ * outlasted its bound.
884
+ *
885
+ * @param {string} ffmpegBin
886
+ * @param {string[]} args
887
+ * @param {number} timeoutMs
888
+ * @returns {Promise<string | null>}
889
+ */
890
+ function runCapturingStderr(ffmpegBin, args, timeoutMs) {
891
+ return new Promise((resolve) => {
892
+ let stderr = "";
893
+ let settled = false;
894
+ let child;
895
+ const settle = (value) => {
896
+ if (settled) {
897
+ return;
898
+ }
899
+ settled = true;
900
+ clearTimeout(timer);
901
+ try {
902
+ child?.kill("SIGKILL");
903
+ } catch {
904
+ // already gone
905
+ }
906
+ resolve(value);
907
+ };
908
+ const timer = setTimeout(() => settle(null), timeoutMs);
909
+ try {
910
+ child = spawn(ffmpegBin, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
911
+ } catch {
912
+ settle(null);
913
+ return;
914
+ }
915
+ child.stderr.on("data", (chunk) => {
916
+ stderr += String(chunk);
917
+ });
918
+ child.on("error", () => settle(null));
919
+ child.on("close", (code) => settle(code === 0 ? stderr : null));
920
+ });
921
+ }
922
+
923
+ /**
924
+ * Measure how fast this host DECODES a clip, from ffmpeg's own report of how
925
+ * much video it has processed.
926
+ *
927
+ * Two things are deliberately outside the measurement.
928
+ *
929
+ * **The process starting.** Wall-clock around the process cannot answer this:
930
+ * starting ffmpeg costs about a second, and on a quick machine a five-second
931
+ * clip decodes in a tenth of that, so the measurement would be of the program
932
+ * starting. Progress lines arrive AFTER it has started, and the slope between
933
+ * two of them video processed against time taken contains no part of the
934
+ * startup by construction.
935
+ *
936
+ * **The clip restarting.** This used to loop the clip with `-stream_loop -1`,
937
+ * and a loop is not free: measured 2026-08-22 on a desktop, a restart costs
938
+ * 0.03 s on the 480p clip and 0.12 s on the 1080p one the decoder tearing
939
+ * down and re-allocating its frame buffers, which is why the price rises with
940
+ * the picture. A five-second clip decoded at 55x restarts eleven times a
941
+ * second, so that cost DOMINATED the reading: the same clips measured 53.7x
942
+ * looped against 80.3x in one continuous pass, and 11.8x against 15.8x. Worse,
943
+ * the bias is not shared it depends on the clip's own resolution and on how
944
+ * fast the host is so it does not cancel out of the fit, it tilts it. That is
945
+ * the fast-host failure recorded on 2026-08-20, where 1080p read cheaper than
946
+ * 720p, which is not a thing a decoder does.
947
+ *
948
+ * So the clip is fed to the decoder as ONE stream instead. An Annex-B
949
+ * elementary stream carries its parameter sets inline, so writing the same
950
+ * bytes again is simply more stream — the decoder never re-initialises, and
951
+ * there is no restart inside the window to measure. Verified against the
952
+ * continuous-pass truth on the same host: -0.2 % and -5.5 %, against -25 % and
953
+ * -33 % for the loop. Nothing is written to disk and the process is killed as
954
+ * soon as the window is wide enough.
955
+ *
956
+ * Exported because the property that broke here is checkable and was not being
957
+ * checked: a bigger picture must cost more than a smaller one of the same
958
+ * bitrate, and under the loop it did not.
959
+ *
960
+ * @param {string} ffmpegBin
961
+ * @param {string} clipPath
962
+ * @param {string} [family="h264"]
963
+ * @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
964
+ */
965
+ export async function measureDecodeSlope(ffmpegBin, clipPath, family = "h264") {
966
+ const streams = await extractFamilyStreams(ffmpegBin, [clipPath], family);
967
+ const stream = streams?.[0];
968
+ if (!stream) {
969
+ return null;
970
+ }
971
+ const measured = await decodePipedStream(ffmpegBin, stream);
972
+ return measured?.speed ? measured : null;
973
+ }
974
+
975
+ /**
976
+ * Decode an elementary stream fed from memory, and report the slope.
977
+ *
978
+ * @param {string} ffmpegBin
979
+ * @param {{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number }} stream
980
+ * @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
981
+ */
982
+ function decodePipedStream(ffmpegBin, stream, log = { info: () => {}, warn: () => {} }) {
983
+ return new Promise((resolve) => {
984
+ const args = [
985
+ "-hide_banner", "-loglevel", "error", "-nostats",
986
+ // A raw stream states no frame rate, so the one the container declared is
987
+ // given back to it. It decides how output time advances, and therefore
988
+ // what "seconds of video per second of clock" means.
989
+ "-f", stream.demuxer, "-framerate", String(stream.fps), "-i", "pipe:0",
990
+ "-an", "-f", "null", "-",
991
+ "-progress", "pipe:1"
992
+ ];
993
+ /** @type {Array<{ wallSec: number, outSec: number }>} */
994
+ const samples = [];
995
+ let stdout = "";
996
+ // Kept because this path depends on three things the old one did not: the
997
+ // raw demuxer accepting the frame rate, the bitstream filter having
998
+ // produced something parsable, and the fed concatenation being decodable.
999
+ // Without it the only trace of any of those failing is "said nothing".
1000
+ let stderr = "";
1001
+ let settled = false;
1002
+ let child;
1003
+ const startedAt = Date.now();
1004
+ // Whether the FEED, not the decoder, could be what this reading measures
1005
+ // (item 4(d2)). `child.stdin.write()` returning false was tried as the
1006
+ // signal never once true would mean this process was never ahead of the
1007
+ // pipe and measured false on every reading taken while writing this,
1008
+ // including clips this same host decodes at 15-80x with room to spare, so
1009
+ // it does not discriminate: `write()`'s return value tracks Node's own
1010
+ // internal watermark against the size of what was just handed to it, not
1011
+ // real drain state, and answered "no slack" identically whether the pipe
1012
+ // or the decoder was the true limit. Rather than publish a verdict that
1013
+ // reads the same in both cases, only the byte count is kept, for the
1014
+ // MB/s figure below a number to read, not a boolean to trust.
1015
+ let bytesWritten = 0;
1016
+ const finish = () => {
1017
+ if (settled) {
1018
+ return;
1019
+ }
1020
+ settled = true;
1021
+ clearTimeout(timer);
1022
+ try {
1023
+ child?.stdin?.destroy();
1024
+ } catch {
1025
+ // already gone
1026
+ }
1027
+ try {
1028
+ child?.kill("SIGKILL");
1029
+ } catch {
1030
+ // already gone
1031
+ }
1032
+ // The first sample still carries the startup — it reports whatever was
1033
+ // processed while the process was coming up. Everything is measured from
1034
+ // the second onwards.
1035
+ const first = samples[1];
1036
+ const last = samples[samples.length - 1];
1037
+ if (!first || !last) {
1038
+ resolve({ error: lastErrorLine(stderr) || "the decoder reported no progress" });
1039
+ return;
1040
+ }
1041
+ const windowSec = last.wallSec - first.wallSec;
1042
+ const producedSec = last.outSec - first.outSec;
1043
+ if (!(windowSec >= DECODE_WINDOW_MIN_SEC) || !(producedSec > 0)) {
1044
+ resolve({ error: lastErrorLine(stderr) || `the window was ${windowSec.toFixed(2)}s of ${producedSec.toFixed(2)}s produced` });
1045
+ return;
1046
+ }
1047
+ const speed = producedSec / windowSec;
1048
+ // Diagnostic only — logged, not acted on. Both figures are taken over the
1049
+ // SAME window the speed itself is: bytesWritten is snapshotted alongside
1050
+ // every progress sample, so this compares like against like rather than
1051
+ // the achieved rate over the whole run (which starts before the first
1052
+ // kept sample and reads systematically low against the window's own
1053
+ // rate for no reason but that mismatch measured while building this).
1054
+ const windowBytes = last.bytesWritten - first.bytesWritten;
1055
+ const achievedMBps = windowSec > 0 ? windowBytes / windowSec / 1e6 : 0;
1056
+ const requiredMBps = ((stream.megabitsPerSecond * 1e6) / 8) * speed / 1e6;
1057
+ // "Far apart" is stated, not left to the reader to eyeball: outside a
1058
+ // factor of 1.5 either way is bigger than the write-timing slop this
1059
+ // comparison carries on a healthy reading.
1060
+ const farApart = requiredMBps > 0 && (achievedMBps / requiredMBps < 1 / 1.5 || achievedMBps / requiredMBps > 1.5);
1061
+ log.info(
1062
+ `hwaccel: decode pipe fed ${achievedMBps.toFixed(1)} MB/s, ${requiredMBps.toFixed(1)} MB/s ` +
1063
+ `needed for ${speed.toFixed(2)}x` +
1064
+ (farApart ? " far enough apart to be worth a second look" : "")
1065
+ );
1066
+ resolve({
1067
+ speed,
1068
+ windowSec,
1069
+ megapixelsPerSecond: stream.megapixelsPerSecond,
1070
+ megabitsPerSecond: stream.megabitsPerSecond,
1071
+ pipeThroughputMBps: achievedMBps
1072
+ });
1073
+ };
1074
+ const timer = setTimeout(finish, DECODE_WINDOW_MAX_MS);
1075
+ try {
1076
+ child = spawn(ffmpegBin, args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1077
+ } catch (error) {
1078
+ clearTimeout(timer);
1079
+ settled = true;
1080
+ resolve({ error: error instanceof Error ? error.message : String(error) });
1081
+ return;
1082
+ }
1083
+ child.stderr.on("data", (chunk) => {
1084
+ stderr += String(chunk);
1085
+ });
1086
+ // Keep the decoder fed. `write` returning false means the pipe is full, and
1087
+ // the next copy goes on the `drain` — so the decoder is never starved and
1088
+ // this process never buffers more than the pipe holds.
1089
+ const writeOnce = () => {
1090
+ const accepted = child.stdin.write(stream.bytes);
1091
+ bytesWritten += stream.bytes.length;
1092
+ return accepted;
1093
+ };
1094
+ const feed = () => {
1095
+ while (!settled && child.stdin.writable && writeOnce()) {
1096
+ // Written straight through; go round again.
1097
+ }
1098
+ };
1099
+ child.stdin.on("drain", feed);
1100
+ // The kill closes the pipe under the writer; that is the intended end.
1101
+ child.stdin.on("error", () => {});
1102
+ child.stdout.on("data", (chunk) => {
1103
+ stdout += String(chunk);
1104
+ let newline = stdout.indexOf("\n");
1105
+ while (newline >= 0) {
1106
+ const line = stdout.slice(0, newline).trim();
1107
+ stdout = stdout.slice(newline + 1);
1108
+ if (line.startsWith("out_time_ms=")) {
1109
+ const microseconds = Number(line.slice("out_time_ms=".length));
1110
+ if (Number.isFinite(microseconds)) {
1111
+ samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec: microseconds / 1e6, bytesWritten });
1112
+ }
1113
+ }
1114
+ newline = stdout.indexOf("\n");
1115
+ }
1116
+ if (samples.length >= 2 && samples[samples.length - 1].wallSec - samples[1].wallSec >= DECODE_WINDOW_MIN_SEC) {
1117
+ finish();
1118
+ }
1119
+ });
1120
+ child.on("error", (error) => {
1121
+ if (settled) {
1122
+ return;
1123
+ }
1124
+ clearTimeout(timer);
1125
+ settled = true;
1126
+ try {
1127
+ child?.stdin?.destroy();
1128
+ } catch {
1129
+ // already gone
1130
+ }
1131
+ try {
1132
+ child?.kill("SIGKILL");
1133
+ } catch {
1134
+ // already gone
1135
+ }
1136
+ resolve({ error: error instanceof Error ? error.message : String(error) });
1137
+ });
1138
+ child.on("close", finish);
1139
+ feed();
1140
+ });
1141
+ }
1142
+
1143
+
1144
+ /**
1145
+ * How many times realtime this host can DECODE a source of these
1146
+ * characteristics, from the startup fit. `null` when the fit is unavailable or
1147
+ * the source figures are not known.
1148
+ *
1149
+ * @param {{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null} model
1150
+ * @param {{ megapixelsPerSecond: number, megabitsPerSecond: number }} source
1151
+ * @returns {number | null}
1152
+ */
1153
+ export function decodeSpeedFor(model, source) {
1154
+ if (!model) {
1155
+ return null;
1156
+ }
1157
+ const pixels = Number(source?.megapixelsPerSecond);
1158
+ const bits = Number(source?.megabitsPerSecond);
1159
+ if (!Number.isFinite(pixels) || pixels <= 0 || !Number.isFinite(bits) || bits < 0) {
1160
+ return null;
1161
+ }
1162
+ const cost = model.pixelTerm * pixels + model.bitrateTerm * bits + model.constantTerm;
1163
+ if (!(cost > 0)) {
1164
+ return null;
1165
+ }
1166
+ return 1 / cost;
1167
+ }
1168
+
1169
+ /**
1170
+ * How many times realtime a re-encode of this source at this output pixel rate
1171
+ * would run: decoding and encoding share the machine, so their costs add and
1172
+ * their speeds combine as
1173
+ *
1174
+ * 1 / (1/decodeSpeed + 1/encodeSpeed)
1175
+ *
1176
+ * Checked 2026-08-14 on the rung that broke playback: 1/(1/2.31 + 1/5.99) =
1177
+ * 1.67× against 1.48× measured. With no decode fit this falls back to the
1178
+ * encode speed alone which is what the budget did before, and which
1179
+ * overestimated that rung five to eleven times.
1180
+ *
1181
+ * @param {{ decodeModel: { pixelTerm: number, bitrateTerm: number, constantTerm: number } | null, encodePixelsPerSec: number, outputPixelsPerSec: number, source: { megapixelsPerSecond: number, megabitsPerSecond: number } | null }} params
1182
+ * @returns {number | null}
1183
+ */
1184
+ export function predictedRealtimeSpeed({
1185
+ decodeModel,
1186
+ encodePixelsPerSec,
1187
+ outputPixelsPerSec,
1188
+ source,
1189
+ observedDecodeCostSec = null
1190
+ }) {
1191
+ if (!Number.isFinite(encodePixelsPerSec) || encodePixelsPerSec <= 0) {
1192
+ return null;
1193
+ }
1194
+ if (!Number.isFinite(outputPixelsPerSec) || outputPixelsPerSec <= 0) {
1195
+ return null;
1196
+ }
1197
+ const encodeSpeed = encodePixelsPerSec / outputPixelsPerSec;
1198
+ // What this very file has been seen to cost, when it has been: the clips are
1199
+ // H.264 and a source that has to be re-encoded usually is not, so a figure
1200
+ // taken from the encoder actually running on THIS source beats any model of
1201
+ // a stand-in. It arrives seconds into playback and replaces the estimate.
1202
+ const decodeSpeed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
1203
+ ? 1 / observedDecodeCostSec
1204
+ : (source ? decodeSpeedFor(decodeModel, source) : null);
1205
+ if (decodeSpeed === null) {
1206
+ return encodeSpeed;
1207
+ }
1208
+ return 1 / (1 / decodeSpeed + 1 / encodeSpeed);
1209
+ }
1210
+
1211
+ /**
1212
+ * Whether this host can hold realtime, with the margin, while re-encoding this
1213
+ * source to this output pixel rate — and the predicted speed either way, so a
1214
+ * refusal can say what it refused on.
1215
+ *
1216
+ * The encoder figure is the FASTEST benchmarked preset: it is the best this
1217
+ * host can do, so a rung it cannot hold cannot be held at any quality setting.
1218
+ *
1219
+ * @param {{ benchmark: Array<{ preset: string, pixelsPerSec: number }>, decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, outputPixelsPerSec: number, requiredSpeed?: number | null }} params
1220
+ * @returns {{ speed: number | null, sustainable: boolean }}
1221
+ */
1222
+ export function canSustainOutput({
1223
+ benchmark,
1224
+ decodeModel = null,
1225
+ source = null,
1226
+ outputPixelsPerSec,
1227
+ observedDecodeCostSec = null,
1228
+ concurrentCostSec = 0,
1229
+ requiredSpeed = null
1230
+ }) {
1231
+ if (!Array.isArray(benchmark) || benchmark.length === 0) {
1232
+ // Nothing measured on this host: the budget cannot refuse what it cannot
1233
+ // price, and refusing everything would leave a viewer with no rung at all.
1234
+ return { speed: null, sustainable: true };
1235
+ }
1236
+ const observed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
1237
+ ? observedDecodeCostSec
1238
+ : null;
1239
+ if (observed === null && !isDecodePriced({ decodeModel, source })) {
1240
+ // An encoder-only figure was several times too optimistic on the rung this
1241
+ // check exists for, so it is not fit to refuse anything. Without the decode
1242
+ // term the ladder is offered whole, exactly as it was before.
1243
+ return { speed: null, sustainable: true };
1244
+ }
1245
+ const alone = predictedRealtimeSpeed({
1246
+ decodeModel,
1247
+ encodePixelsPerSec: cheapestPresetPixelsPerSec(benchmark),
1248
+ outputPixelsPerSec,
1249
+ source,
1250
+ observedDecodeCostSec: observed
1251
+ });
1252
+ // What ELSE will be running while this rung is. A rung is never the only
1253
+ // thing on the machine: the picture it accompanies is being copied or
1254
+ // encoded, an audio track may have its own encoder, and a warm-up is two
1255
+ // encoders by design. Measured on the addon host, a copy alone takes about an
1256
+ // eighth of the machine per second of video, and the field case of
1257
+ // 2026-08-15 adds up exactly: 0.125 for the copy plus ~1.05 for the rung is
1258
+ // more than the one second per second the machine has, which is what was
1259
+ // observed.
1260
+ //
1261
+ // Zero when nothing else is known to be running, or when nothing has been
1262
+ // measured yet — then this is a LOWER bound on the cost and the check is as
1263
+ // permissive as it was before.
1264
+ const speed = alone === null || !(concurrentCostSec > 0)
1265
+ ? alone
1266
+ : 1 / (1 / alone + concurrentCostSec);
1267
+ if (speed === null) {
1268
+ return { speed: null, sustainable: true };
1269
+ }
1270
+ return { speed, sustainable: speed >= speedBar(requiredSpeed) };
1271
+ }
1272
+
1273
+ /**
1274
+ * The speed a step has to reach to be worth offering.
1275
+ *
1276
+ * Realtime is not enough on its own: a step that produces exactly one second
1277
+ * per second never recovers the seconds lost while its reader waits for the
1278
+ * swarm, so it survives its own supply only if what it gains between
1279
+ * interruptions covers what one interruption costs. That is measured per file
1280
+ * and per swarm by the reader `1 + worst wait / median interval`, in
1281
+ * `supply-margin.js` and on the field torrent of 2026-08-17 it came to 1.67
1282
+ * against the 1.5 that used to stand here, and to 4.04-8.14 on a torrent whose
1283
+ * swarm no encoder could have kept up with.
1284
+ *
1285
+ * Where that figure does not exist yet — fewer than two interruptions measured
1286
+ * — the bar is realtime. It is the one thing that can be said without
1287
+ * measuring the swarm, and the offer is restated as soon as the reader has
1288
+ * something to say.
1289
+ *
1290
+ * @param {number | null | undefined} requiredSpeed - What this file's own
1291
+ * interruptions demand, when they have been measured.
1292
+ * @returns {number}
1293
+ */
1294
+ export function speedBar(requiredSpeed) {
1295
+ return Number.isFinite(requiredSpeed) && requiredSpeed > REALTIME ? requiredSpeed : REALTIME;
1296
+ }
1297
+
1298
+ /**
1299
+ * The bar for a cost description — the supply's demand where decoding is
1300
+ * priced, and never below the unpriced-decode bar where it is not.
1301
+ *
1302
+ * @param {{ decodeModel?: object | null, source?: object | null, observedDecodeCostSec?: number | null, requiredSpeed?: number | null }} cost
1303
+ * @returns {number}
1304
+ */
1305
+ function barFor(cost) {
1306
+ const measured = speedBar(cost?.requiredSpeed);
1307
+ return isDecodePriced(cost) ? measured : Math.max(UNPRICED_DECODE_BAR, measured);
1308
+ }
1309
+
1310
+ /**
1311
+ * Benchmark software libx264 presets on this host. Encodes a short synthetic
1312
+ * clip at a fixed reference resolution with each preset and measures encoder
1313
+ * throughput in pixels/second. The session manager uses this to pick, per
1314
+ * stream, the highest-quality preset that still encodes the actual
1315
+ * (source-capped) resolution faster than realtime.
1316
+ *
1317
+ * Runs once at startup; bounded by a per-encode timeout. Presets that fail are
1318
+ * omitted from the result.
1319
+ *
1320
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
1321
+ * @returns {Promise<Array<{ preset: string, pixelsPerSec: number }>>} Ordered slowest→fastest.
1322
+ */
1323
+ export async function benchmarkSoftwarePresets({ ffmpegBin, logger, encoder = null }) {
1324
+ const log = logger ?? { info: () => {}, warn: () => {} };
1325
+
1326
+ // REAL footage, decoded ONCE into raw frames, and the presets are then timed
1327
+ // on those frames.
1328
+ //
1329
+ // Two reasons, both measured. The pattern this replaced (`testsrc2`) has flat
1330
+ // areas and no grain and encodes 1.23x cheaper than film on the same machine
1331
+ // and preset an error that always points at offering a rung the host cannot
1332
+ // hold. And feeding a compressed clip to each preset instead would put
1333
+ // decoding and scaling inside the measurement: subtracting them afterwards
1334
+ // compares a wall clock that includes process startup against a decode figure
1335
+ // measured to exclude it, while inside one ffmpeg the two halves overlap. On
1336
+ // the fastest preset the one every ladder decision reads as the ceiling —
1337
+ // that subtraction is most of the number being measured, so a small error in
1338
+ // it becomes a large error in the answer.
1339
+ //
1340
+ // Raw frames remove all of it: no decoder, no scaler, nothing to subtract,
1341
+ // and no dependence on the decode model. The cost is 25 MB of memory in a
1342
+ // pipe for a few seconds.
1343
+ const rawFramesPath = await decodeToRawFrames(ffmpegBin, log);
1344
+ if (rawFramesPath === null) {
1345
+ // Said once more, in the words that matter to whoever reads the log next:
1346
+ // with no benchmark, `#sustainableHeights` filters nothing and every rung
1347
+ // is offered, which is the failure of 2026-08-14 in full.
1348
+ log.warn("hwaccel: the quality ladder is UNFILTERED on this host — nothing measured the encoder");
1349
+ return [];
1350
+ }
1351
+ /** @type {Array<{ preset: string, pixelsPerSec: number }>} */
1352
+ const results = [];
1353
+ try {
1354
+ // THE CHOSEN ENCODER'S OWN LADDER, whatever kind it is. NVENC walks p1…p7,
1355
+ // QSV veryfast…veryslow, VAAPI its quality levels. A kind with no ladder is
1356
+ // measured once, which is still a reading where there was none at all.
1357
+ const ladder = encoder?.speedLadder;
1358
+ const rungs = Array.isArray(ladder?.values) && ladder.values.length > 0 ? ladder.values : [null];
1359
+ for (const rung of rungs) {
1360
+ const speed = await measureEncodeSlope(ffmpegBin, encoder, rung, rawFramesPath);
1361
+ if (speed === null) {
1362
+ log.warn(`hwaccel: the benchmark of "${rung ?? encoder?.name}" produced no usable reading; skipping`);
1363
+ continue;
1364
+ }
1365
+ const pixelsPerSec = BENCHMARK_REF_W * BENCHMARK_REF_H * TRANSCODE_FPS * speed;
1366
+ results.push({ preset: rung ?? encoder?.name, pixelsPerSec });
1367
+ log.info(
1368
+ `hwaccel: ${encoder?.name} "${rung ?? "as it comes"}" ~= ${(pixelsPerSec / 1e6).toFixed(1)} Mpx/s ` +
1369
+ `(${speed.toFixed(2)}x @ ${BENCHMARK_REF_W}x${BENCHMARK_REF_H}, real footage)`
1370
+ );
1371
+ }
1372
+ } finally {
1373
+ // The encoder was killed a moment ago and on Windows the handle outlives
1374
+ // the signal, so removal is retried and its failure is not worth a session:
1375
+ // this is a temp directory the operating system will clear anyway.
1376
+ try {
1377
+ rmSync(path.dirname(rawFramesPath), { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
1378
+ } catch (error) {
1379
+ log.warn(`hwaccel: could not remove the benchmark's raw frames: ${error instanceof Error ? error.message : String(error)}`);
1380
+ }
1381
+ }
1382
+ return results;
1383
+ }
1384
+
1385
+ /**
1386
+ * How fast one preset encodes, from ffmpeg's own reports of how much video it
1387
+ * has written not from the clock around the process.
1388
+ *
1389
+ * Timing whole runs measures the run STARTING. Measured 2026-08-15 on a desktop
1390
+ * that spawns ffmpeg in ~0.4 s: three seconds of raw frames encoded that way
1391
+ * put `fast` and `ultrafast` within 1.24x of each other, when libx264's own
1392
+ * presets differ by several times the constant had swallowed the difference.
1393
+ * The slope between two progress reports contains no part of the startup.
1394
+ *
1395
+ * The frames are written repeatedly so there is runway to measure over,
1396
+ * whatever the preset's speed.
1397
+ *
1398
+ * @param {string} ffmpegBin
1399
+ * @param {string} preset
1400
+ * @param {string} rawFramesPath
1401
+ * @returns {Promise<number | null>} Video seconds encoded per second of clock.
1402
+ */
1403
+ /**
1404
+ * Video seconds produced per second of clock, from ffmpeg's own reports.
1405
+ *
1406
+ * Startup is excluded by taking a DIFFERENCE: it lands in the wall clock of
1407
+ * every report equally, so it cancels between two of them. (The decode
1408
+ * benchmark drops its first report instead, because there the first one is
1409
+ * emitted at out_time zero; here reports with no time yet are discarded before
1410
+ * they arrive, so the first kept one is already running.)
1411
+ *
1412
+ * @param {Array<{ wallSec: number, outSec: number }>} samples
1413
+ * @param {number} [minimumWindowSec=ENCODE_BENCHMARK_WINDOW_SEC]
1414
+ * @returns {number | null}
1415
+ */
1416
+ export function slopeOf(samples, minimumWindowSec = ENCODE_BENCHMARK_WINDOW_SEC) {
1417
+ const first = samples[0];
1418
+ const last = samples[samples.length - 1];
1419
+ if (!first || !last || first === last) {
1420
+ return null;
1421
+ }
1422
+ const took = last.wallSec - first.wallSec;
1423
+ const produced = last.outSec - first.outSec;
1424
+ if (!(took >= minimumWindowSec) || !(produced > 0)) {
1425
+ return null;
1426
+ }
1427
+ const slope = produced / took;
1428
+ // Nothing encodes a thousand times realtime. A figure above that is a
1429
+ // measurement fault, and letting it through opens the whole ladder.
1430
+ return slope <= ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED ? slope : null;
1431
+ }
1432
+
1433
+ function measureEncodeSlope(ffmpegBin, encoder, rung, rawFramesPath) {
1434
+ return new Promise((resolve) => {
1435
+ const args = [
1436
+ "-hide_banner", "-loglevel", "error", "-nostats",
1437
+ // What a device-backed encoder needs before the input — the device. Not
1438
+ // its decoding setup: this is fed raw frames and there is nothing to
1439
+ // decode, and `-hwaccel vaapi` over rawvideo fails to open.
1440
+ ...(typeof encoder?.benchmarkInputArgs === "function" ? encoder.benchmarkInputArgs() : []),
1441
+ "-stream_loop", "-1",
1442
+ "-f", "rawvideo", "-pix_fmt", "yuv420p",
1443
+ "-s", `${BENCHMARK_REF_W}x${BENCHMARK_REF_H}`, "-r", String(TRANSCODE_FPS),
1444
+ "-i", rawFramesPath,
1445
+ // THE ENCODER SAYS HOW TO MEASURE ITSELF. It was libx264 written here, so
1446
+ // a host with NVENC, QSV, VAAPI or V4L2M2M measured its encoder not at all
1447
+ // and the quality offer, which is arithmetic over pixels per second, had
1448
+ // no pixels per second to work with.
1449
+ ...encoder.benchmarkArgs(rung),
1450
+ "-f", "null", "-",
1451
+ "-progress", "pipe:1"
1452
+ ];
1453
+ /** @type {Array<{ wallSec: number, outSec: number }>} */
1454
+ const samples = [];
1455
+ let settled = false;
1456
+ let buffered = "";
1457
+ let child;
1458
+ const startedAt = Date.now();
1459
+ const finish = (value) => {
1460
+ if (settled) {
1461
+ return;
1462
+ }
1463
+ settled = true;
1464
+ clearTimeout(timer);
1465
+ try {
1466
+ child?.kill("SIGKILL");
1467
+ } catch {
1468
+ // already gone
1469
+ }
1470
+ resolve(value);
1471
+ };
1472
+ const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
1473
+ try {
1474
+ child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1475
+ } catch {
1476
+ finish(null);
1477
+ return;
1478
+ }
1479
+ // The frames come from a FILE, read on repeat by ffmpeg itself. Fed through
1480
+ // a pipe instead, the fastest presets measured the pipe: `ultrafast` on a
1481
+ // desktop wants raw frames at hundreds of megabytes a second, which no
1482
+ // writer here can supply, and the reading then describes the feeding rather
1483
+ // than the encoder.
1484
+ child.stdout.on("data", (chunk) => {
1485
+ buffered += String(chunk);
1486
+ let newline = buffered.indexOf(NEWLINE);
1487
+ while (newline >= 0) {
1488
+ const line = buffered.slice(0, newline).trim();
1489
+ buffered = buffered.slice(newline + 1);
1490
+ if (line.startsWith("out_time_ms=")) {
1491
+ const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
1492
+ // `N/A` is not the only way ffmpeg says "no position yet": some builds
1493
+ // print the smallest signed 64-bit integer, which IS finite and would
1494
+ // be taken for a position nine trillion seconds before the start.
1495
+ if (Number.isFinite(outSec) && outSec >= 0) {
1496
+ samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
1497
+ }
1498
+ }
1499
+ newline = buffered.indexOf(NEWLINE);
1500
+ }
1501
+ const slope = slopeOf(samples);
1502
+ if (slope !== null) {
1503
+ finish(slope);
1504
+ }
1505
+ });
1506
+ child.on("error", () => finish(null));
1507
+ // A preset that finished before the window was wide enough is measured from
1508
+ // whatever it did report, provided two reports exist at all.
1509
+ // A preset that finished before the wide window was covered is still
1510
+ // measured — but never over a window of nothing. Two reports a millisecond
1511
+ // apart would divide a frame of video by that millisecond and call the host
1512
+ // twenty times faster than it is, and one such reading becomes the figure
1513
+ // every ladder decision is taken from.
1514
+ child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
1515
+ });
1516
+ }
1517
+
1518
+ /**
1519
+ * The benchmark's footage as raw frames: the calibration clip, looped to the
1520
+ * benchmark's length and scaled to its size, decoded once.
1521
+ *
1522
+ * @param {string} ffmpegBin
1523
+ * @param {{ info: (m: string) => void, warn: (m: string) => void }} log
1524
+ * @returns {Promise<string | null>} Path to the raw frames, or null.
1525
+ */
1526
+ async function decodeToRawFrames(ffmpegBin, log) {
1527
+ // A benchmark may leave a host unmeasured; it may never stop it from
1528
+ // starting. Before this the temp directory was made outside any guard, so a
1529
+ // read-only or missing TMPDIR rejected the promise that starts the proxy.
1530
+ let directory;
1531
+ try {
1532
+ directory = mkdtempSync(path.join(os.tmpdir(), "torrent-tv-bench-"));
1533
+ } catch (error) {
1534
+ log.warn(
1535
+ `hwaccel: no writable temp directory for the preset benchmark (${error instanceof Error ? error.message : String(error)}); ` +
1536
+ "presets unmeasured, so no quality rung will be refused on this host"
1537
+ );
1538
+ return null;
1539
+ }
1540
+ const rawPath = path.join(directory, "frames.yuv");
1541
+ const args = [
1542
+ "-hide_banner", "-loglevel", "error",
1543
+ "-stream_loop", "-1",
1544
+ "-i", path.join(CALIBRATION_DIR, CALIBRATION_CLIPS[0]),
1545
+ "-t", String(BENCHMARK_DURATION_SEC),
1546
+ "-vf", `scale=${BENCHMARK_REF_W}:${BENCHMARK_REF_H},fps=${TRANSCODE_FPS}`,
1547
+ "-an", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-y", rawPath
1548
+ ];
1549
+ const { code } = await runFfmpeg(ffmpegBin, args, 30000);
1550
+ const expectedBytes = BENCHMARK_REF_W * BENCHMARK_REF_H * 1.5 * TRANSCODE_FPS * BENCHMARK_DURATION_SEC;
1551
+ let written = 0;
1552
+ try {
1553
+ written = statSync(rawPath).size;
1554
+ } catch {
1555
+ written = 0;
1556
+ }
1557
+ if (code !== 0 || written < expectedBytes * 0.9) {
1558
+ log.warn(
1559
+ "hwaccel: could not decode the calibration clip for the preset benchmark " +
1560
+ `(${written} of ~${Math.round(expectedBytes)} bytes); presets unmeasured, ` +
1561
+ "so no quality rung will be refused on this host"
1562
+ );
1563
+ try {
1564
+ rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
1565
+ } catch {
1566
+ // A temp directory the operating system will clear; not worth a start-up.
1567
+ }
1568
+ return null;
1569
+ }
1570
+ return rawPath;
1571
+ }
1572
+
1573
+ /**
1574
+ * Pick the highest-quality (slowest) benchmarked preset that can encode
1575
+ * `pixelsPerSecNeeded` with the speed margin. Falls back to the fastest
1576
+ * benchmarked preset, or `"ultrafast"` when no benchmark is available.
1577
+ *
1578
+ * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
1579
+ * @param {number} pixelsPerSecNeeded
1580
+ * @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
1581
+ * @returns {string}
1582
+ */
1583
+ /**
1584
+ * What this host can do at its CHEAPEST preset — the ceiling of the ladder.
1585
+ *
1586
+ * Deliberately not the largest reading in the array. The list is in quality
1587
+ * order, so its last measured entry is the cheapest preset; taking the maximum
1588
+ * instead would let one noisy reading of an expensive preset raise the bar that
1589
+ * decides which rungs are offered, and a rung offered on noise is a rung the
1590
+ * host cannot hold. For choosing a preset the direction of that error is
1591
+ * harmless; for deciding what to offer it is not, so the two use different
1592
+ * statistics on purpose.
1593
+ *
1594
+ * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark
1595
+ * @returns {number}
1596
+ */
1597
+ function cheapestPresetPixelsPerSec(benchmark) {
1598
+ return benchmark[benchmark.length - 1]?.pixelsPerSec ?? 0;
1599
+ }
1600
+
1601
+ export function pickSoftwarePreset(benchmark, pixelsPerSecNeeded, cost = {}) {
1602
+ if (!Array.isArray(benchmark) || benchmark.length === 0) {
1603
+ return "ultrafast";
1604
+ }
1605
+ const observed = Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0
1606
+ ? cost.observedDecodeCostSec
1607
+ : null;
1608
+ const bar = barFor(cost);
1609
+ // The FIRST entry that clears the bar wins — the list is in quality order, so
1610
+ // that is the best picture this host can hold. Every entry is examined rather
1611
+ // than the walk stopping at the first miss, because the measurements do not
1612
+ // always ascend with the list: on a busy machine on 2026-08-15 `faster` read
1613
+ // below `fast` twice.
1614
+ for (const entry of benchmark) {
1615
+ const speed = predictedRealtimeSpeed({
1616
+ decodeModel: cost.decodeModel ?? null,
1617
+ encodePixelsPerSec: entry.pixelsPerSec,
1618
+ outputPixelsPerSec: pixelsPerSecNeeded,
1619
+ source: cost.source ?? null,
1620
+ observedDecodeCostSec: observed
1621
+ });
1622
+ if (speed !== null && speed >= bar) {
1623
+ return entry.preset;
1624
+ }
1625
+ }
1626
+ // Nothing clears the bar: the cheapest preset, which is the last in quality
1627
+ // order. Returning whichever preset measured fastest would hand an expensive
1628
+ // one to a host that has just been shown to hold no rung at all.
1629
+ return benchmark[benchmark.length - 1].preset;
1630
+ }
1631
+
1632
+ /**
1633
+ * Whether a cost description can actually price decoding — a fit AND a source
1634
+ * to apply it to. Without both, every prediction is encoder-only.
1635
+ *
1636
+ * @param {{ decodeModel?: object | null, source?: object | null }} cost
1637
+ * @returns {boolean}
1638
+ */
1639
+ function isDecodePriced(cost) {
1640
+ if (Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0) {
1641
+ return true; // measured on the source itself, which needs no fit to stand on
1642
+ }
1643
+ return Boolean(cost?.decodeModel) && Boolean(cost?.source);
1644
+ }
1645
+
1646
+ // Resolution-ladder heights (output height rungs), high→low. The ladder is
1647
+ // derived per-stream from the ceiling (the client-requested, source-capped
1648
+ // output box): only rungs at or below the ceiling height are used, so the
1649
+ // budget never upscales past what the client asked for. Standard heights keep
1650
+ // the downscaled output at familiar resolutions.
1651
+ const RESOLUTION_LADDER_HEIGHTS = [2160, 1440, 1080, 720, 540, 480, 360, 240];
1652
+
1653
+ /**
1654
+ * Build the resolution ladder for a ceiling box. Returns candidate output
1655
+ * dimensions from the ceiling downward, preserving the ceiling's aspect ratio,
1656
+ * each even-sized. The ceiling itself is always the top rung; ladder heights
1657
+ * at or above it are skipped (never upscale). Deduped by height.
1658
+ *
1659
+ * @param {number} ceilingWidth
1660
+ * @param {number} ceilingHeight
1661
+ * @returns {Array<{ width: number, height: number }>} high→low
1662
+ */
1663
+ export function buildResolutionLadder(ceilingWidth, ceilingHeight) {
1664
+ const cw = Number.isInteger(ceilingWidth) && ceilingWidth > 0 ? ceilingWidth : 0;
1665
+ const ch = Number.isInteger(ceilingHeight) && ceilingHeight > 0 ? ceilingHeight : 0;
1666
+ if (!cw || !ch) {
1667
+ return [];
1668
+ }
1669
+ const even = (v) => {
1670
+ const r = Math.round(v);
1671
+ return Math.max(2, r - (r % 2));
1672
+ };
1673
+ /** @type {Array<{ width: number, height: number }>} */
1674
+ const rungs = [{ width: cw, height: ch }];
1675
+ for (const h of RESOLUTION_LADDER_HEIGHTS) {
1676
+ if (h >= ch) {
1677
+ continue; // at/above the ceiling — the ceiling rung already covers it
1678
+ }
1679
+ rungs.push({ width: even(cw * (h / ch)), height: h });
1680
+ }
1681
+ const seen = new Set();
1682
+ return rungs.filter((rung) => {
1683
+ if (seen.has(rung.height)) {
1684
+ return false;
1685
+ }
1686
+ seen.add(rung.height);
1687
+ return true;
1688
+ });
1689
+ }
1690
+
1691
+ /**
1692
+ * Choose the software encode settings (resolution + preset) that fit the
1693
+ * realtime budget on this host. From the resolution ladder (ceiling downward),
1694
+ * pick the HIGHEST rung whose encode throughput predicted from the startup
1695
+ * benchmark's fastest preset clears the speed this file's own supply
1696
+ * demands (`speedBar`). Then, at that resolution, pick the highest-quality
1697
+ * preset that still clears it. When even the lowest rung cannot clear it, use the lowest rung with
1698
+ * the fastest preset (best effort a smaller picture beats sub-realtime
1699
+ * playback at full size). Returns null when no benchmark or ceiling is
1700
+ * available (the caller keeps the ceiling resolution and the default preset).
1701
+ *
1702
+ * @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
1703
+ * @param {{ width: number, height: number }} ceiling
1704
+ * @param {number} outputFps
1705
+ * @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
1706
+ * @returns {{ width: number, height: number, preset: string, ladder: Array<{ width: number, height: number }>, rungIndex: number } | null}
1707
+ */
1708
+ export function chooseSoftwareEncodeSettings(benchmark, ceiling, outputFps, cost = {}) {
1709
+ if (!Array.isArray(benchmark) || benchmark.length === 0) {
1710
+ return null;
1711
+ }
1712
+ const fps = Number.isFinite(outputFps) && outputFps > 0 ? outputFps : TRANSCODE_FPS;
1713
+ const ladder = buildResolutionLadder(ceiling?.width, ceiling?.height);
1714
+ if (ladder.length === 0) {
1715
+ return null;
1716
+ }
1717
+ const fastest = cheapestPresetPixelsPerSec(benchmark); // the cheapest preset's throughput
1718
+ const bar = barFor(cost);
1719
+ let chosenIndex = ladder.length - 1; // default: lowest rung (best effort)
1720
+ for (let i = 0; i < ladder.length; i += 1) {
1721
+ const speed = predictedRealtimeSpeed({
1722
+ decodeModel: cost.decodeModel ?? null,
1723
+ encodePixelsPerSec: fastest,
1724
+ outputPixelsPerSec: ladder[i].width * ladder[i].height * fps,
1725
+ source: cost.source ?? null
1726
+ });
1727
+ if (speed !== null && speed >= bar) {
1728
+ chosenIndex = i;
1729
+ break;
1730
+ }
1731
+ }
1732
+ const chosen = ladder[chosenIndex];
1733
+ const preset = pickSoftwarePreset(benchmark, chosen.width * chosen.height * fps, cost);
1734
+ return { width: chosen.width, height: chosen.height, preset, ladder, rungIndex: chosenIndex };
1735
+ }
1736
+
1737
+ /**
1738
+ * How fast this machine COPIES a picture, in seconds of film per second.
1739
+ *
1740
+ * The startup measurements price encoding and decoding, and a copied picture
1741
+ * does neither: it reads packets and writes them out again. That left one whole
1742
+ * branch of what this proxy does with no figure at all, and a figure is what
1743
+ * every decision in the encoding layer is made from where to put an encoder,
1744
+ * how many to run, whether anybody will be left waiting. Without it a copied
1745
+ * output was planned with no speed until its own run had been running long
1746
+ * enough to report one, which is exactly the moment the plan matters most.
1747
+ *
1748
+ * Measured the same way as the others: ffmpeg's own progress, read as a slope
1749
+ * over a window, so the process starting is outside the figure.
1750
+ *
1751
+ * The clip is joined to itself first rather than looped with `-stream_loop`.
1752
+ * Looping charges a re-initialisation per lap — measured on the addon host at
1753
+ * 0.03 s for 480p and 0.12 s for 1080p and a copy of a five-second clip laps
1754
+ * many times a second, so the reading would have been mostly re-initialisation.
1755
+ *
1756
+ * @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} params
1757
+ * @returns {Promise<number | null>} Seconds of film per second, or null where
1758
+ * the reading could not be taken. Null means unmeasured and is never a
1759
+ * substitute for a number.
1760
+ */
1761
+ export async function benchmarkCopySpeed({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
1762
+ const log = logger ?? { info: () => {}, warn: () => {} };
1763
+ const startedAt = Date.now();
1764
+ // The largest clip in the set. A copy moves BYTES, so what it can do is a
1765
+ // statement about the biggest pictures this host will be asked to pass
1766
+ // through, and the small ones are covered by the same figure.
1767
+ const clip = path.join(clipsDir, "cal-h264-1080-hi.mp4");
1768
+ const speed = await measureCopySlope(ffmpegBin, clip);
1769
+ if (!(speed > 0)) {
1770
+ log.warn("hwaccel: copying could not be measured; a copied picture will be planned from its own run instead");
1771
+ return null;
1772
+ }
1773
+ log.info(
1774
+ `hwaccel: this host copies a picture at ${speed.toFixed(0)}x realtime ` +
1775
+ `(measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
1776
+ );
1777
+ return speed;
1778
+ }
1779
+
1780
+ /**
1781
+ * Seconds of film per second, copying one file, read from ffmpeg's progress.
1782
+ *
1783
+ * @param {string} ffmpegBin
1784
+ * @param {string} filePath
1785
+ * @returns {Promise<number | null>}
1786
+ */
1787
+ function measureCopySlope(ffmpegBin, filePath) {
1788
+ return new Promise((resolve) => {
1789
+ const args = [
1790
+ "-hide_banner", "-loglevel", "error", "-nostats",
1791
+ // Played over and over, because a copy gets through a five-second clip in
1792
+ // milliseconds and a slope needs a window to be taken over. Looping
1793
+ // charges the demuxer being re-opened once a lap, so what comes out is a
1794
+ // FLOOR on what this host can copy — the safe direction, since a plan made
1795
+ // from it expects copying to be slower than it is.
1796
+ "-stream_loop", "-1", "-i", filePath,
1797
+ // What a copied output does: packets in, packets out, nothing decoded and
1798
+ // nothing encoded. Written nowhere, so the figure is this machine's own
1799
+ // handling and not the disk under a temp directory.
1800
+ "-c", "copy", "-f", "null", "-",
1801
+ // Progress is reported every half second by default, which over a window
1802
+ // of one second is two readings. This asks for twenty.
1803
+ "-stats_period", "0.05",
1804
+ "-progress", "pipe:1"
1805
+ ];
1806
+ /** @type {Array<{ wallSec: number, outSec: number }>} */
1807
+ const samples = [];
1808
+ let settled = false;
1809
+ let buffered = "";
1810
+ let child;
1811
+ const startedAt = Date.now();
1812
+ const finish = (value) => {
1813
+ if (settled) {
1814
+ return;
1815
+ }
1816
+ settled = true;
1817
+ clearTimeout(timer);
1818
+ try {
1819
+ child?.kill("SIGKILL");
1820
+ } catch {
1821
+ // already gone
1822
+ }
1823
+ resolve(value);
1824
+ };
1825
+ const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
1826
+ try {
1827
+ child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1828
+ } catch {
1829
+ finish(null);
1830
+ return;
1831
+ }
1832
+ child.stdout.on("data", (chunk) => {
1833
+ buffered += String(chunk);
1834
+ let newline = buffered.indexOf(NEWLINE);
1835
+ while (newline >= 0) {
1836
+ const line = buffered.slice(0, newline).trim();
1837
+ buffered = buffered.slice(newline + 1);
1838
+ if (line.startsWith("out_time_ms=")) {
1839
+ const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
1840
+ if (Number.isFinite(outSec) && outSec >= 0) {
1841
+ samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
1842
+ }
1843
+ }
1844
+ newline = buffered.indexOf(NEWLINE);
1845
+ }
1846
+ const slope = slopeOf(samples);
1847
+ if (slope !== null) {
1848
+ finish(slope);
1849
+ }
1850
+ });
1851
+ child.on("error", () => finish(null));
1852
+ child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
1853
+ });
1854
+ }