From f1b554a3291890dabd17fc87777c86ef4ca8cfc5 Mon Sep 17 00:00:00 2001 From: Joan Leon Date: Fri, 27 Nov 2026 08:20:06 +0100 Subject: [PATCH] feat: add a budget mode that compares quality at equal file size --target-bytes searches each codec for the largest file that fits a byte budget (KB/MB decimal, KiB/MiB binary, or a bare byte count) and ranks codecs by the ssimulacra2 they reach there. The search reads only the encoded size, so it decodes and scores once per codec, which makes a budget run about half as long as an equal-quality run on the demo images. The batch summary averages quality over the images where every codec fits, so codecs are ranked on the same images. Tables, summary and CSV are supported; --html, --rd and --target are rejected alongside it. --- README.md | 7 ++ ROADMAP.md | 5 +- compare/README.md | 36 ++++++ compare/bin/compare.js | 134 +++++++++++++++++---- compare/src/batch.js | 57 +++++++++ compare/src/budget.js | 25 ++++ compare/src/pipeline.js | 187 +++++++++++++++++++---------- compare/src/report.js | 123 +++++++++++++++++++ compare/src/search.js | 56 +++++++++ compare/test/budget.test.js | 36 ++++++ compare/test/integration.test.js | 80 +++++++++++- compare/test/report-budget.test.js | 119 ++++++++++++++++++ compare/test/search.test.js | 77 +++++++++++- 13 files changed, 854 insertions(+), 88 deletions(-) create mode 100644 compare/src/budget.js create mode 100644 compare/test/budget.test.js create mode 100644 compare/test/report-budget.test.js diff --git a/README.md b/README.md index 5c407c5..d289305 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ compare-codecs [options] --max-iterations Max search steps per codec (default: 10) --effort <0..10> Matched encoder effort across codecs (jxl/avif/webp); higher = slower --time-runs Time each codec's encode n times, report the median (default: 1) + --target-bytes Budget mode: search every codec for the largest file that + fits this size (50KB = 50,000 bytes, 50KiB = 51,200, or a + bare byte count) and compare the ssimulacra2 each reaches. + Replaces --target; not available with --rd or --html --rd Rate-distortion mode: search every codec at each target in the list, report bpp per target and BD-rate vs mozjpeg; with --html, the report plots these curves @@ -96,6 +100,9 @@ compare-codecs images/ --target 90 --csv results.csv # Interactive report: wipe, format toggle, difference view, rate–distortion chart, quality slider compare-codecs images/ --target 90 --html report.html +# Budget: the best quality each codec reaches within 30 KB (equal size, compare quality) +compare-codecs images/ --target-bytes 30KB --csv budget.csv + # Rate-distortion: bpp at several quality targets and BD-rate vs mozjpeg compare-codecs images/ --rd 70,80,85,90,95 --csv rd.csv diff --git a/ROADMAP.md b/ROADMAP.md index b6df130..a2f0b60 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,13 +4,12 @@ This is a lightweight list of ideas under consideration. Nothing here is committ ## Status -The current state is stable: `compare-codecs` supports six codecs (JPEG XL, AVIF, WebP, jpegli, mozjpeg, HEIC) with equal-quality search, batch mode, CSV output, per-codec encode timing, matched encoder effort (`--effort`), a rate-distortion mode (`--rd`) with BD-rate against mozjpeg, and a self-contained interactive HTML report with a difference view and a rate–distortion chart that, with `--rd`, plots the equal-quality curves and BD-rates. All three test layers (unit, gated integration, and the image E2E build) run in CI, alongside a size-regression gate against a committed baseline that comments on pull requests, and a weekly comparison report on the demo images, a set of seven covering photographs, a flat illustration, a high-detail texture, a UI screenshot and a diagram. The comparison and the regression gate are also packaged as a GitHub Action, [Compare image codecs](https://github.com/nucliweb/compare-codecs-action), for use on other repositories' images. +The current state is stable: `compare-codecs` supports six codecs (JPEG XL, AVIF, WebP, jpegli, mozjpeg, HEIC) with equal-quality search, batch mode, CSV output, per-codec encode timing, matched encoder effort (`--effort`), a rate-distortion mode (`--rd`) with BD-rate against mozjpeg, a budget mode (`--target-bytes`) that compares quality at equal file size, and a self-contained interactive HTML report with a difference view and a rate–distortion chart that, with `--rd`, plots the equal-quality curves and BD-rates. All three test layers (unit, gated integration, and the image E2E build) run in CI, alongside a size-regression gate against a committed baseline that comments on pull requests, and a weekly comparison report on the demo images, a set of seven covering photographs, a flat illustration, a high-detail texture, a UI screenshot and a diagram. The comparison and the regression gate are also packaged as a GitHub Action, [Compare image codecs](https://github.com/nucliweb/compare-codecs-action), for use on other repositories' images. ## Ideas ### Features -- **Target-size mode.** Answer the inverse question of the equal-quality search: given a byte budget (`--target-bytes 50KB`), which codec looks best? The search runs on each codec's quality knob towards a file size instead of a score, then reports the ssimulacra2 each one reaches at that size. This is the question a web performance budget asks. The budget should state its unit explicitly, KB (1000 bytes) or KiB (1024 bytes), and the result should say whether it was met. A later step could add downscaling as a second lever, for budgets that quality alone cannot reach. - **Rate-distortion curves by default in the HTML report.** Without `--rd`, the report's chart is still a coarse fixed-knob sweep. Making the equal-quality curves the default would drop the sweep, at the cost of one search per target instead of five fixed encodes per codec. - **More codecs.** Extend beyond the current six as encoders mature or new ones become relevant. Low effort per codec, since the equal-quality search already generalises across quality knobs. A candidate is [jixel](https://github.com/awxkee/jixel), a second JPEG XL encoder (Rust, BSD-3-Clause, ported from libjxl-tiny) that [JPEG XL vs AVIF for web use-cases](https://jakearchibald.com/2026/jpeg-xl-vs-avif/) finds much closer to AVIF than libjxl on photographs; as an opt-in variant it would repeat the rav1e and SVT-AV1 lesson for JPEG XL. It has no CLI, so the image would build a small wrapper. - **Tool versions in the results.** Write the encoder, decoder and metric versions into the CSV and the HTML report, so a result read outside the Docker image still says which builds produced it, together with the SHA-256 of each input image. A JSON output with a `schemaVersion` field would carry the same provenance for scripts and the GitHub Action, which today parse the CSV. @@ -18,6 +17,8 @@ The current state is stable: `compare-codecs` supports six codecs (JPEG XL, AVIF - **An independent second metric.** Optionally score every result with [ColorVideoVDP](https://github.com/gfxdisp/ColorVideoVDP), from a lab with no tie to any codec, as a cross-check on ssimulacra2 where JPEG XL and another format are close. It is a Python and PyTorch install of about 1 GB, so it would stay outside the default image. - **Decode with platform decoders.** Measure what users actually see: decode with the platform's own decoder (Apple ImageIO through `sips`, browsers) as well as the reference decoders, and time the decode. The HEIC 4:2:0 lesson already shows a 1.5–8.4 point gap between libheif and ImageIO, and decode speed is part of the trade-off ([JPEG XL vs AVIF for web use-cases](https://jakearchibald.com/2026/jpeg-xl-vs-avif/) measures it in Firefox, Chrome and Safari). +- **Budget mode in the HTML report.** `--target-bytes` prints tables and a CSV; the report compares codecs at equal quality, so budget runs have no visual comparison yet. A later step could add downscaling as a second lever, for budgets that quality alone cannot reach. + ### Demo material - **An image with alpha.** The seven demo images are all opaque RGB. Transparency changes the comparison (some encoders store alpha losslessly, which [JPEG XL vs AVIF for web use-cases](https://jakearchibald.com/2026/jpeg-xl-vs-avif/) shows costing jixel 136% against AVIF), so the set should include one image with an alpha channel. diff --git a/compare/README.md b/compare/README.md index 01cc08e..b811544 100644 --- a/compare/README.md +++ b/compare/README.md @@ -43,6 +43,7 @@ Options: | `--max-iterations ` | `10` | Maximum search steps per codec | | `--effort <0..10>` | codec default | Matched encoder effort across codecs that have the knob (higher = slower) | | `--time-runs ` | `1` | Time each codec's encode n times and report the median | +| `--target-bytes ` | — | [Budget mode](#budget-mode): search each codec for the largest file that fits this size (`50KB` = 50,000 bytes, `50KiB` = 51,200, or a bare byte count) and compare quality; replaces `--target`, not available with `--rd` or `--html` | | `--rd ` | — | Rate-distortion mode: search each codec at every target in the list; with `--html`, the report shows the encodes at the target closest to `--target` | | `--csv ` | — | Also write the results as CSV | | `--html ` | — | Write an interactive, self-contained HTML report | @@ -84,6 +85,39 @@ compare-codecs images/ --rd 70,80,85,90,95 --html rd.html Its chart dots are the equal-quality encodes at each target, the same points as the table and the CSV, and the readout under the chart and the across-all-images summary add each codec's BD-rate and mean BD-rate. The viewer shows each codec's encode at the target closest to `--target` (90 by default), so pass a list that includes the quality you want to inspect. +## Budget mode + +The default comparison fixes the quality and compares sizes. A web performance budget asks the inverse question: with **50 KB to spend**, which codec looks best? `--target-bytes` searches each codec's quality knob for the largest file that fits the budget, then compares the ssimulacra2 each one reaches there: + +```bash +compare-codecs images/ --target-bytes 30KB --csv budget.csv +``` + +The budget takes its unit explicitly: `KB` and `MB` are decimal (`30KB` is 30,000 bytes), `KiB` and `MiB` are binary (`30KiB` is 30,720 bytes), and a bare number is a byte count. Each table states the budget both ways, gives sizes in exact bytes, and ranks codecs by quality, best first: + +``` +Budget: 30 KB = 30,000 bytes (equal size; compare quality, higher ssimulacra2 is better). + ++---------+--------------+----------+-----------+-------+-------------+---------+-------+--------+--------+----------+-----------+-----------+ +| Codec | Setting | Size | of budget | bpp | ssimulacra2 | dssim | iters | encode | cpu | memory | enc total | cpu total | ++---------+--------------+----------+-----------+-------+-------------+---------+-------+--------+--------+----------+-----------+-----------+ +| AVIF | --min/max 31 | 29,224 B | 97.4% | 0.244 | 76.52 | 0.00105 | 6 | 530 ms | 660 ms | 135.4 MB | 5.92 s | 7.45 s | +| HEIC | -q 29 | 29,263 B | 97.5% | 0.244 | 61.80 | 0.00259 | 5 | 290 ms | 280 ms | 42.2 MB | 3.17 s | 3.13 s | +| JPEG XL | -d 8.95 | 29,817 B | 99.4% | 0.248 | 54.81 | 0.00407 | 7 | 90 ms | 500 ms | 95.3 MB | 740 ms | 3.80 s | +| WebP | -q 33 | 29,934 B | 99.8% | 0.249 | 48.69 | 0.00486 | 6 | 40 ms | 40 ms | 8.6 MB | 280 ms | 250 ms | +| mozjpeg | -quality 27 | 29,885 B | 99.6% | 0.249 | 31.16 | 0.01084 | 6 | 40 ms | 30 ms | 7.9 MB | 270 ms | 240 ms | +| jpegli | -d 14.97 | 30,395 B | 101.3% * | 0.253 | 23.55 | 0.01330 | 9 | 20 ms | 10 ms | 13.6 MB | 210 ms | 130 ms | ++---------+--------------+----------+-----------+-------+-------------+---------+-------+--------+--------+----------+-----------+-----------+ + +* cannot fit the budget even at its lowest quality setting; smallest file shown. +``` + +That is `report-ui.png`, the 1200×800 UI screenshot, in the Docker image. At 30 KB, AVIF keeps it at ssimulacra2 76.5, while mozjpeg falls to 31.2. `of budget` is the share of the budget the file uses: the search stops within 1% under the budget, but a codec whose quality knob moves in coarse steps can land lower, since the next step up would exceed it. A file over the budget is never chosen while one under it exists. When even the codec's lowest quality setting is over the budget, as for jpegli here, the row shows that smallest file, flagged `*`, and ranks after every codec that fits. + +With more than one image, a **budget summary** follows: each codec's average ssimulacra2, its wins (the best quality among the codecs that fit an image), its mean difference in ssimulacra2 points from mozjpeg, and on how many images it fits. The averages and the difference cover only the images where **every** codec fits, the same images for all, and the summary says how many those are: averaging each codec over its own images would rank them on different sets and reward a codec for failing to fit the hardest ones. `--csv` writes one row per image and codec (`image,codec,setting,budget_bytes,bytes,bpp,ssimulacra2,dssim,fits,iterations`, then the timing columns and `error`). + +The search only needs the file size, so it encodes without decoding or measuring, and decodes and scores once, at the chosen setting; on the seven demo images, a 30 KB budget run takes about half as long as an equal-quality run at the default target (29 s against 63 s on an Apple Silicon laptop). `--codecs`, `--effort`, `--time-runs` and `--max-iterations` apply as usual; `--tolerance` is a ssimulacra2 tolerance and does not apply. The HTML report compares codecs at equal quality, so `--html` is not available in budget mode. + ## Interactive HTML report `--html report.html` produces a single self-contained file (images embedded, no @@ -374,6 +408,8 @@ the PNG to its critical chunks (so every codec's output is readable by ssimulacr measure, and adjust. If the target is outside a codec's reachable range, it settles at the closest bound (visible as `iters` hitting the max with the knob pinned). +In [budget mode](#budget-mode) the same knob is searched against the encoded size instead, which grows with quality in the same direction as the score: encode, read the size, and adjust towards the largest file under the budget. + ## Scope and assumptions - Input is a PNG in sRGB. Ancillary chunks (ICC profile, chromaticities) are stripped diff --git a/compare/bin/compare.js b/compare/bin/compare.js index 2e689a1..4b1c524 100755 --- a/compare/bin/compare.js +++ b/compare/bin/compare.js @@ -4,13 +4,14 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, basename } from "node:path"; import { CODECS, DEFAULT_CODECS, resolveCodecIds } from "../src/codecs.js"; -import { findQualityForTarget } from "../src/pipeline.js"; +import { findQualityForTarget, findQualityForBudget } from "../src/pipeline.js"; import { pngDimensions, writeStrippedPng, pngDataUri } from "../src/image.js"; import { run, resolveCommand, failureReason } from "../src/exec.js"; -import { collectImages, aggregate } from "../src/batch.js"; +import { collectImages, aggregate, aggregateBudget } from "../src/batch.js"; import { sweepCodec } from "../src/sweep.js"; import { buildHtml } from "../src/report-html.js"; import { parseTargets, aggregateBdRates, imageBdRates } from "../src/rd.js"; +import { parseByteSize } from "../src/budget.js"; import { toComparisonTable, toCsv, @@ -19,6 +20,9 @@ import { toRdTable, toRdAggregateTable, toRdCsv, + toBudgetTable, + toBudgetAggregateTable, + toBudgetCsv, } from "../src/report.js"; const USAGE = `Usage: compare-codecs [options] @@ -34,10 +38,15 @@ Options: -c, --codecs Comma-separated (default: ${DEFAULT_CODECS.join(",")}); opt-in variants: ${Object.keys(CODECS).filter((id) => !DEFAULT_CODECS.includes(id)).join(",")}; "all" runs every codec and variant - --tolerance Stop when within this of the target (default: 0.5) + --tolerance Stop when within this of the target (default: 0.5); budget + mode stops within 1% under the budget --max-iterations Max search steps per codec (default: 10) --effort <0..10> Matched encoder effort across codecs (jxl/avif/webp); higher = slower --time-runs Time each codec's encode n times, report the median (default: 1) + --target-bytes Budget mode: search every codec for the largest file that + fits this size (50KB = 50,000 bytes, 50KiB = 51,200, or a + bare byte count) and compare the ssimulacra2 each reaches. + Replaces --target; not available with --rd or --html --rd Rate-distortion mode: search every codec at each of these targets (e.g. 70,80,85,90,95), report bpp per target and BD-rate vs mozjpeg. With --html, the report plots these @@ -60,7 +69,10 @@ function parse() { const { values, positionals } = parseArgs({ allowPositionals: true, options: { - target: { type: "string", short: "t", default: "90" }, + // No default here, so an explicit --target can be told apart from the 90 + // applied in main() and rejected alongside --target-bytes. + target: { type: "string", short: "t" }, + "target-bytes": { type: "string" }, codecs: { type: "string", short: "c" }, tolerance: { type: "string", default: "0.5" }, "max-iterations": { type: "string", default: "10" }, @@ -85,7 +97,7 @@ function main() { process.exit(values.help ? 0 : 1); } - const target = Number(values.target); + const target = Number(values.target ?? "90"); const tolerance = Number(values.tolerance); const maxIterations = Number(values["max-iterations"]); const timeRuns = Math.max(1, Math.floor(Number(values["time-runs"])) || 1); @@ -106,6 +118,28 @@ function main() { process.exit(1); } } + let budget = null; + if (values["target-bytes"] !== undefined) { + // Equal size and equal quality are two different comparisons: one run makes one. + const conflict = + values.target !== undefined + ? "--target-bytes and --target are two modes (equal size, equal quality); use one." + : rdTargets + ? "--target-bytes and --rd are two modes (equal size, equal-quality curves); use one." + : values.html + ? "--html is not available with --target-bytes: the report compares codecs at equal quality." + : null; + if (conflict) { + console.error(conflict); + process.exit(1); + } + try { + budget = parseByteSize(values["target-bytes"]); + } catch (err) { + console.error(err.message); + process.exit(1); + } + } let ids; try { ids = resolveCodecIds(values.codecs); @@ -145,6 +179,10 @@ function main() { const searchOpts = { tolerance, maxIterations, timeRuns, effort }; const baselineId = ids.includes("mozjpeg") ? "mozjpeg" : ids[0]; const baselineName = CODECS[baselineId]?.name ?? baselineId; + if (budget) { + runBudget(images, ids, budget, workdir, searchOpts, { baselineId, baselineName, csv: values.csv, effort }); + return; + } if (rdTargets) { runRd(images, ids, rdTargets, workdir, searchOpts, { baselineId, baselineName, csv: values.csv, html: values.html, target, embed }); return; @@ -155,15 +193,9 @@ function main() { const perImage = []; const report = { target, images: [] }; images.forEach((image, idx) => { - const refNorm = join(workdir, `img${idx}.norm.png`); - let dims; - try { - writeStrippedPng(image, refNorm); - dims = pngDimensions(refNorm); - } catch { - process.stderr.write(`Skipping (not a PNG in sRGB): ${image}\n`); - return; - } + const prepared = prepareReference(image, idx, workdir); + if (!prepared) return; + const { refNorm, dims } = prepared; process.stderr.write(`# ${basename(image)}\n`); const results = []; @@ -252,6 +284,68 @@ function main() { } } +/** + * Normalize one input image into the work directory (critical chunks only, the + * reference every codec is measured against) and read its size. Returns null, after + * saying so, for a file that is not a usable PNG, so a batch skips it and goes on. + */ +function prepareReference(image, idx, workdir) { + const refNorm = join(workdir, `img${idx}.norm.png`); + try { + writeStrippedPng(image, refNorm); + return { refNorm, dims: pngDimensions(refNorm) }; + } catch { + process.stderr.write(`Skipping (not a PNG in sRGB): ${image}\n`); + return null; + } +} + +/** + * Budget mode: search every codec on every image for the largest file that fits + * the byte budget, then print one table per image (quality at equal size), a batch + * summary, and optionally a CSV. + */ +function runBudget(images, ids, budget, workdir, searchOpts, { baselineId, baselineName, csv, effort }) { + const perImage = []; + images.forEach((image, idx) => { + const prepared = prepareReference(image, idx, workdir); + if (!prepared) return; + const { refNorm, dims } = prepared; + + process.stderr.write(`# ${basename(image)}\n`); + const results = ids.map((id) => { + const codec = CODECS[id]; + process.stderr.write(` → ${codec.name} …\n`); + try { + return findQualityForBudget(codec, image, budget.bytes, workdir, { ...searchOpts, referenceNorm: refNorm }); + } catch (err) { + const error = failureReason(err); + process.stderr.write(` ! ${codec.name} failed on ${basename(image)}: ${error}\n`); + return { id, name: codec.name, failed: true, error }; + } + }); + perImage.push({ image: basename(image), width: dims.width, height: dims.height, results }); + }); + + if (perImage.length === 0) { + console.error("No usable PNG images."); + process.exit(1); + } + + const meta = { budgetBytes: budget.bytes, budgetLabel: budget.label, effort }; + console.log(perImage.map((p) => toBudgetTable(p.results, { ...meta, reference: p.image, width: p.width, height: p.height })).join("\n\n")); + + if (perImage.length > 1) { + const rows = aggregateBudget(perImage, { baselineId }); + console.log(`\n${toBudgetAggregateTable(rows, { ...meta, imageCount: perImage.length, baselineId, baselineName })}`); + } + + if (csv) { + writeFileSync(csv, `${toBudgetCsv(perImage)}\n`); + process.stderr.write(`Wrote ${csv}\n`); + } +} + /** * Rate-distortion mode: run the equal-quality search for every image, codec and * target, then print one RD table per image (bpp per target and BD-rate vs the @@ -266,15 +360,9 @@ function runRd(images, ids, targets, workdir, searchOpts, { baselineId, baseline const perImage = []; const reportImages = []; images.forEach((image, idx) => { - const refNorm = join(workdir, `img${idx}.norm.png`); - let dims; - try { - writeStrippedPng(image, refNorm); - dims = pngDimensions(refNorm); - } catch { - process.stderr.write(`Skipping (not a PNG in sRGB): ${image}\n`); - return; - } + const prepared = prepareReference(image, idx, workdir); + if (!prepared) return; + const { refNorm, dims } = prepared; process.stderr.write(`# ${basename(image)}\n`); const previews = new Map(); diff --git a/compare/src/batch.js b/compare/src/batch.js index b7f48ba..2a685c9 100644 --- a/compare/src/batch.js +++ b/compare/src/batch.js @@ -79,3 +79,60 @@ export function aggregate(perImage, { baselineId } = {}) { })) .sort((a, b) => (a.avgBpp ?? Infinity) - (b.avgBpp ?? Infinity)); } + +/** + * Aggregate per-image budget results (equal size) into a per-codec summary. + * + * The average ssimulacra2 and the mean difference from a baseline codec cover only + * the images where every codec fit the budget, the same images for all, so codecs + * are ranked on like for like: averaging each codec over its own images would + * reward one for failing to fit the hardest ones. Wins (best quality among the + * codecs that fit an image) and the fit count cover every image. Sorted by average + * ssimulacra2 (best first). + * + * @param {Array<{ image: string, results: Array }>} perImage + * @param {{ baselineId?: string }} [opts] + * @returns {Array<{ id, name, avgScore, deltaVsBaseline, wins, fits, count, compared }>} + * `compared` is the number of images the averages cover. + */ +export function aggregateBudget(perImage, { baselineId } = {}) { + const byId = new Map(); + const fitsImage = (r) => !r.failed && r.fits; + let compared = 0; + + for (const { results } of perImage) { + const fitting = results.filter(fitsImage); + const winner = fitting.reduce((best, r) => (!best || r.ssimulacra2 > best.ssimulacra2 ? r : best), null); + const everyCodecFits = fitting.length === results.length; + const baseline = baselineId ? fitting.find((r) => r.id === baselineId) : null; + if (everyCodecFits) compared += 1; + + for (const r of results) { + let entry = byId.get(r.id); + if (!entry) { + entry = { id: r.id, name: r.name, scores: [], deltas: [], wins: 0, fits: 0, count: 0 }; + byId.set(r.id, entry); + } + entry.count += 1; + if (!fitsImage(r)) continue; + entry.fits += 1; + if (r === winner) entry.wins += 1; + if (!everyCodecFits) continue; + entry.scores.push(r.ssimulacra2); + if (baseline) entry.deltas.push(r.ssimulacra2 - baseline.ssimulacra2); + } + } + + return [...byId.values()] + .map((e) => ({ + id: e.id, + name: e.name, + avgScore: e.scores.length ? mean(e.scores) : null, + deltaVsBaseline: e.deltas.length ? mean(e.deltas) : null, + wins: e.wins, + fits: e.fits, + count: e.count, + compared, + })) + .sort((a, b) => (b.avgScore ?? -Infinity) - (a.avgScore ?? -Infinity)); +} diff --git a/compare/src/budget.js b/compare/src/budget.js new file mode 100644 index 0000000..c552e23 --- /dev/null +++ b/compare/src/budget.js @@ -0,0 +1,25 @@ +// Decimal units are powers of 1000 and binary units powers of 1024, as in IEC +// 80000-13: "50KB" and "50KiB" are different budgets, 50,000 and 51,200 bytes. +const UNITS = { + b: { factor: 1, label: "B" }, + kb: { factor: 1000, label: "KB" }, + mb: { factor: 1000 ** 2, label: "MB" }, + kib: { factor: 1024, label: "KiB" }, + mib: { factor: 1024 ** 2, label: "MiB" }, +}; + +/** + * Parse a --target-bytes value such as "50KB", "48 KiB", "1.5MB" or "48000" (a + * bare number is bytes). A fractional byte count is rounded down, so a file that + * meets the parsed budget also meets the one asked for. + * @returns {{ bytes: number, label: string }} + */ +export function parseByteSize(value) { + const match = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i.exec(value); + const unit = match ? UNITS[(match[2] || "b").toLowerCase()] : undefined; + const bytes = unit ? Math.floor(Number(match[1]) * unit.factor) : NaN; + if (!(bytes >= 1)) { + throw new Error(`--target-bytes must be a size such as 50KB, 48KiB or 48000 (bytes), at least one byte; got "${value}".`); + } + return { bytes, label: `${match[1]} ${unit.label}` }; +} diff --git a/compare/src/pipeline.js b/compare/src/pipeline.js index 3a5ffc7..19f61e5 100644 --- a/compare/src/pipeline.js +++ b/compare/src/pipeline.js @@ -3,7 +3,7 @@ import { join } from "node:path"; import { run, runTimed, resolveCommand } from "./exec.js"; import { buildEncodeArgs } from "./codecs.js"; import { ssimulacra2, dssim } from "./metrics.js"; -import { searchForTarget } from "./search.js"; +import { searchForTarget, searchForBudget } from "./search.js"; import { pngDimensions, writeStrippedPng } from "./image.js"; /** @@ -18,6 +18,23 @@ export function encoderInput(codec, referencePng) { return converted; } +/** + * Encode the reference at a given knob and read the encoded size, timing the + * encoder (wall and CPU) and its peak memory. + * @returns {{ encoded, bytes, encodeWallMs, encodeCpuMs, encodePeakBytes }} + */ +function encodeAt(codec, referencePng, knob, workdir, tag, effort) { + const encoded = join(workdir, `${codec.id}${tag}.${codec.ext}`); + const timing = runTimed(resolveCommand(codec.encoder), buildEncodeArgs(codec, encoderInput(codec, referencePng), encoded, knob, effort)); + return { + encoded, + bytes: statSync(encoded).size, + encodeWallMs: timing.wallMs, + encodeCpuMs: timing.cpuMs, + encodePeakBytes: timing.peakBytes, + }; +} + /** * Encode the reference at a given knob, decode back to PNG, strip the decoded * PNG to critical chunks (so ssimulacra2 can read every codec's output), and @@ -28,22 +45,14 @@ export function encoderInput(codec, referencePng) { * @returns {{ score, bytes, decodedPng, encodeWallMs, encodeCpuMs, encodePeakBytes }} */ export function encodeDecodeMeasure(codec, referencePng, knob, workdir, tag = "", effort = null) { - const encoded = join(workdir, `${codec.id}${tag}.${codec.ext}`); const decodedRaw = join(workdir, `${codec.id}${tag}.dec.raw.png`); const decodedPng = join(workdir, `${codec.id}${tag}.dec.png`); - const timing = runTimed(resolveCommand(codec.encoder), buildEncodeArgs(codec, encoderInput(codec, referencePng), encoded, knob, effort)); + const { encoded, ...encode } = encodeAt(codec, referencePng, knob, workdir, tag, effort); run(resolveCommand(codec.decoder), codec.decodeArgs(encoded, decodedRaw)); writeStrippedPng(decodedRaw, decodedPng); - return { - score: ssimulacra2(referencePng, decodedPng), - bytes: statSync(encoded).size, - decodedPng, - encodeWallMs: timing.wallMs, - encodeCpuMs: timing.cpuMs, - encodePeakBytes: timing.peakBytes, - }; + return { score: ssimulacra2(referencePng, decodedPng), decodedPng, ...encode }; } /** @@ -79,6 +88,74 @@ export function medianEncodeTiming(codec, referencePng, knob, workdir, runs, eff return { wallMs: median(wall), cpuMs: median(cpu), peakBytes }; } +/** + * Normalize the reference once, unless the caller already did: strip ancillary + * chunks so ssimulacra2/dssim can read it, and so every codec is measured against + * the exact same input. + */ +function normalizedReference(referencePng, workdir, opts) { + if (opts.referenceNorm) return opts.referenceNorm; + const refNorm = join(workdir, "reference.norm.png"); + writeStrippedPng(referencePng, refNorm); + return refNorm; +} + +/** + * Accumulate the encoder's own time across every encode a search performs, plus + * the final one, for a per-codec "total encode effort". If any sample is missing + * (no /usr/bin/time) the total is reported as null rather than an undercount. + */ +function encodeEffort() { + let wallMs = 0; + let cpuMs = 0; + let complete = true; + return { + add(m) { + if (m.encodeWallMs === null || m.encodeCpuMs === null) complete = false; + else { + wallMs += m.encodeWallMs; + cpuMs += m.encodeCpuMs; + } + }, + totals: () => ({ totalEncodeWallMs: complete ? wallMs : null, totalEncodeCpuMs: complete ? cpuMs : null }), + }; +} + +/** + * Re-encode at the chosen knob to read the definitive size and decoded output, + * time it, and assemble the fields both searches report. + * + * Timing reuses the final encode's sample for the default single run (no extra + * work); for more runs, it re-times the encode and reports the median to cut noise. + */ +function measureOperatingPoint(codec, refNorm, knob, workdir, effort, iterations, effortLog, opts) { + const final = encodeDecodeMeasure(codec, refNorm, knob, workdir, "", effort); + effortLog.add(final); + + const timeRuns = Math.max(1, Math.floor(opts.timeRuns ?? 1)); + const timing = + timeRuns > 1 + ? medianEncodeTiming(codec, refNorm, knob, workdir, timeRuns, effort) + : { wallMs: final.encodeWallMs, cpuMs: final.encodeCpuMs, peakBytes: final.encodePeakBytes }; + + return { + id: codec.id, + name: codec.name, + label: codec.label(knob), + knob, + ssimulacra2: final.score, + dssim: dssim(refNorm, final.decodedPng), + bytes: final.bytes, + bpp: (final.bytes * 8) / pngDimensions(refNorm).pixels, + iterations, + decodedPng: final.decodedPng, + encodeWallMs: timing.wallMs, + encodeCpuMs: timing.cpuMs, + encodePeakBytes: timing.peakBytes, + ...effortLog.totals(), + }; +} + /** * Search a codec's quality knob until the decoded image reaches the target * ssimulacra2 score, then report size and metrics at that operating point. @@ -87,70 +164,58 @@ export function medianEncodeTiming(codec, referencePng, knob, workdir, runs, eff * decodedPng, encodeWallMs, encodeCpuMs, encodePeakBytes, totalEncodeWallMs, totalEncodeCpuMs }} */ export function findQualityForTarget(codec, referencePng, target, workdir, opts = {}) { - // Normalize the reference once: strip ancillary chunks so ssimulacra2/dssim can - // read it, and so every codec is measured against the exact same input. - const refNorm = opts.referenceNorm ?? join(workdir, "reference.norm.png"); - if (!opts.referenceNorm) writeStrippedPng(referencePng, refNorm); - const { pixels } = pngDimensions(refNorm); + const refNorm = normalizedReference(referencePng, workdir, opts); const effort = opts.effort ?? null; - - // Accumulate the encoder's own time across every encode the search performs, plus - // the final one, for a per-codec "total encode effort". If any sample is missing - // (no /usr/bin/time) the total is reported as null rather than an undercount. - let totalWallMs = 0; - let totalCpuMs = 0; - let timingComplete = true; - const addEncode = (m) => { - if (m.encodeWallMs === null || m.encodeCpuMs === null) timingComplete = false; - else { - totalWallMs += m.encodeWallMs; - totalCpuMs += m.encodeCpuMs; - } - }; + const tolerance = opts.tolerance ?? 0.5; + const effortLog = encodeEffort(); const search = searchForTarget({ lo: codec.knob.lo, hi: codec.knob.hi, target, - tolerance: opts.tolerance ?? 0.5, + tolerance, maxIterations: opts.maxIterations ?? 10, increasing: codec.knob.increasing, evaluate: (knob) => { const m = encodeDecodeMeasure(codec, refNorm, knob, workdir, "", effort); - addEncode(m); + effortLog.add(m); return m.score; }, }); - // Re-encode at the chosen knob to read the definitive size and decoded output. - const final = encodeDecodeMeasure(codec, refNorm, search.value, workdir, "", effort); - addEncode(final); - const tolerance = opts.tolerance ?? 0.5; + const op = measureOperatingPoint(codec, refNorm, search.value, workdir, effort, search.iterations, effortLog, opts); + return { ...op, reached: Math.abs(op.ssimulacra2 - target) <= tolerance }; +} - // Timing: reuse the final encode's sample for the default single run (no extra - // work); for more runs, re-time the encode and report the median to cut noise. - const timeRuns = Math.max(1, Math.floor(opts.timeRuns ?? 1)); - const timing = - timeRuns > 1 - ? medianEncodeTiming(codec, refNorm, search.value, workdir, timeRuns, effort) - : { wallMs: final.encodeWallMs, cpuMs: final.encodeCpuMs, peakBytes: final.encodePeakBytes }; +/** + * Search a codec's quality knob for the largest file that fits a byte budget, + * then report the quality it reaches there: the inverse of findQualityForTarget, + * comparing codecs at equal size instead of equal quality. + * + * The search only needs the encoded size, so it encodes without decoding or + * measuring; the decode and the metrics run once, at the chosen setting. + * + * @returns {{ ...findQualityForTarget's fields except reached, budgetBytes: number, + * fits: boolean }} `fits` is false when even the lowest quality is over budget. + */ +export function findQualityForBudget(codec, referencePng, budgetBytes, workdir, opts = {}) { + const refNorm = normalizedReference(referencePng, workdir, opts); + const effort = opts.effort ?? null; + const effortLog = encodeEffort(); - return { - id: codec.id, - name: codec.name, - label: codec.label(search.value), - knob: search.value, - ssimulacra2: final.score, - dssim: dssim(refNorm, final.decodedPng), - bytes: final.bytes, - bpp: (final.bytes * 8) / pixels, - iterations: search.iterations, - reached: Math.abs(final.score - target) <= tolerance, - decodedPng: final.decodedPng, - encodeWallMs: timing.wallMs, - encodeCpuMs: timing.cpuMs, - encodePeakBytes: timing.peakBytes, - totalEncodeWallMs: timingComplete ? totalWallMs : null, - totalEncodeCpuMs: timingComplete ? totalCpuMs : null, - }; + const search = searchForBudget({ + lo: codec.knob.lo, + hi: codec.knob.hi, + budget: budgetBytes, + maxIterations: opts.maxIterations ?? 10, + increasing: codec.knob.increasing, + evaluate: (knob) => { + const m = encodeAt(codec, refNorm, knob, workdir, "", effort); + effortLog.add(m); + return m.bytes; + }, + }); + + const op = measureOperatingPoint(codec, refNorm, search.value, workdir, effort, search.iterations, effortLog, opts); + return { ...op, budgetBytes, fits: op.bytes <= budgetBytes }; } diff --git a/compare/src/report.js b/compare/src/report.js index 184bb87..5d3cdcc 100644 --- a/compare/src/report.js +++ b/compare/src/report.js @@ -260,3 +260,126 @@ export function toRdCsv(perImageRd) { } return [head, ...lines].join("\n"); } + +const formatExactBytes = (bytes) => `${bytes.toLocaleString("en-US")} B`; +const budgetLine = (meta) => `${meta.budgetLabel} = ${meta.budgetBytes.toLocaleString("en-US")} bytes`; + +/** + * Budget results in display order: the codecs that fit, best quality first; then + * those over the budget (smallest first, the closest to fitting); then failures. + */ +const budgetOrder = (results) => { + const measured = results.filter((r) => !r.failed); + return [ + ...measured.filter((r) => r.fits).sort((a, b) => b.ssimulacra2 - a.ssimulacra2), + ...measured.filter((r) => !r.fits).sort(bySizeAscending), + ...results.filter((r) => r.failed), + ]; +}; + +/** + * Render budget results (every codec searched to the largest file that fits a byte + * budget) as an ASCII table: equal size, so the comparison is by quality, best + * first. A codec that could not fit the budget is flagged and ranked after the rest. + */ +export function toBudgetTable(results, meta) { + const rows = budgetOrder(results); + const columns = [ + { header: "Codec", align: "left" }, + { header: "Setting", align: "left" }, + { header: "Size", align: "right" }, + { header: "of budget", align: "right" }, + { header: "bpp", align: "right" }, + { header: "ssimulacra2", align: "right" }, + { header: "dssim", align: "right" }, + { header: "iters", align: "right" }, + { header: "encode", align: "right" }, + { header: "cpu", align: "right" }, + { header: "memory", align: "right" }, + { header: "enc total", align: "right" }, + { header: "cpu total", align: "right" }, + ]; + const body = rows.map((r) => + r.failed + ? [r.name, "—", "failed", ...Array(columns.length - 3).fill("—")] + : [ + r.name, + r.label, + formatExactBytes(r.bytes), + `${((r.bytes / meta.budgetBytes) * 100).toFixed(1)}%${r.fits ? "" : " *"}`, + r.bpp.toFixed(3), + r.ssimulacra2.toFixed(2), + r.dssim.toFixed(5), + String(r.iterations), + formatDuration(r.encodeWallMs), + formatDuration(r.encodeCpuMs), + formatMemory(r.encodePeakBytes), + formatDuration(r.totalEncodeWallMs), + formatDuration(r.totalEncodeCpuMs), + ], + ); + const heading = [ + `Codec comparison — ${meta.reference} (${meta.width}×${meta.height})`, + `Budget: ${budgetLine(meta)} (equal size; compare quality, higher ssimulacra2 is better).`, + ...(meta.effort === null || meta.effort === undefined + ? [] + : [`Effort: ${meta.effort} (matched where supported; codecs without an effort knob use their default).`]), + "", + ]; + const footnote = rows.some((r) => !r.failed && !r.fits) + ? ["", "* cannot fit the budget even at its lowest quality setting; smallest file shown."] + : []; + const failures = failureNotes(rows.filter((r) => r.failed)); + return [...heading, asciiTable(columns, body), ...footnote, ...failures].join("\n"); +} + +const formatPoints = (delta) => (delta === null ? "n/a" : `${delta > 0 ? "+" : ""}${delta.toFixed(2)}`); + +/** Render the per-codec budget summary over a batch of images as an ASCII table. */ +export function toBudgetAggregateTable(rows, meta) { + const baseline = meta.baselineName ?? "baseline"; + const columns = [ + { header: "Codec", align: "left" }, + { header: "avg ssimulacra2", align: "right" }, + { header: "wins", align: "right" }, + { header: `vs ${baseline}`, align: "right" }, + { header: "fits budget", align: "right" }, + ]; + const body = rows.map((r) => [ + r.name, + r.avgScore === null ? "n/a" : r.avgScore.toFixed(2), + String(r.wins), + r.id === meta.baselineId ? "baseline" : formatPoints(r.deltaVsBaseline), + `${r.fits}/${r.count}`, + ]); + const compared = rows[0]?.compared ?? 0; + const scope = + compared > 0 + ? `Averages and the difference from ${baseline} (in ssimulacra2 points) cover the ${compared} of ${meta.imageCount} images where every codec fits; wins and fits count every image.` + : "No image fits the budget with every codec, so there are no averages to compare; wins and fits count every image."; + const heading = [`Budget summary — ${meta.imageCount} images, budget ${budgetLine(meta)}`, scope, ""]; + return [...heading, asciiTable(columns, body)].join("\n"); +} + +const BUDGET_FIELDS = [ + (r) => csvField(r.label), + (r) => r.budgetBytes, + (r) => r.bytes, + (r) => r.bpp.toFixed(4), + (r) => r.ssimulacra2.toFixed(4), + (r) => r.dssim.toFixed(6), + (r) => r.fits, + ...SINGLE_FIELDS.slice(5), +]; + +/** Render budget results as CSV, one row per (image, codec), in table order. */ +export function toBudgetCsv(perImage) { + const head = + "image,codec,setting,budget_bytes,bytes,bpp,ssimulacra2,dssim,fits,iterations," + + "encode_wall_ms,encode_cpu_ms,total_encode_wall_ms,total_encode_cpu_ms,encode_peak_rss_bytes,error"; + const lines = []; + for (const { image, results } of perImage) { + for (const r of budgetOrder(results)) lines.push(`${csvField(image)},${csvRow(r, BUDGET_FIELDS)}`); + } + return [head, ...lines].join("\n"); +} diff --git a/compare/src/search.js b/compare/src/search.js index a8d1f24..3bf3930 100644 --- a/compare/src/search.js +++ b/compare/src/search.js @@ -49,3 +49,59 @@ export function searchForTarget({ return best; } + +/** + * Binary-search a quality knob for the largest encoded size that fits a byte + * budget. The size is assumed monotonic in the knob in the same direction as the + * score (`increasing` as for searchForTarget), since a higher quality costs bytes. + * + * The constraint is one-sided: an evaluation over the budget is never returned + * while one under it has been seen. When nothing fits, the smallest file seen is + * returned with `fits: false`, so a budget below the codec's range resolves to its + * lowest-quality end. + * + * @param {object} opts + * @param {number} opts.lo + * @param {number} opts.hi + * @param {number} opts.budget Maximum size in bytes. + * @param {number} [opts.tolerance] Stop once the size is within this many bytes + * under the budget (default: 1% of the budget). + * @param {number} [opts.maxIterations] + * @param {boolean} [opts.increasing] Whether the size increases with the knob. + * @param {(knob: number) => number} opts.evaluate Encodes at a knob, returns bytes. + * @returns {{ value: number, bytes: number, iterations: number, fits: boolean }} + */ +export function searchForBudget({ + lo, + hi, + budget, + tolerance = budget * 0.01, + maxIterations = 12, + increasing = true, + evaluate, +}) { + let best = null; + + for (let i = 0; i < maxIterations; i += 1) { + const mid = (lo + hi) / 2; + const bytes = evaluate(mid); + const fits = bytes <= budget; + + const better = fits + ? best === null || !best.fits || bytes > best.bytes + : best === null || (!best.fits && bytes < best.bytes); + if (better) best = { value: mid, bytes, iterations: i + 1, fits }; + + if (fits && budget - bytes <= tolerance) break; + + // Under the budget there is room for more quality; over it, less. + const raiseKnob = increasing === fits; + if (raiseKnob) { + lo = mid; + } else { + hi = mid; + } + } + + return best; +} diff --git a/compare/test/budget.test.js b/compare/test/budget.test.js new file mode 100644 index 0000000..4fdcedf --- /dev/null +++ b/compare/test/budget.test.js @@ -0,0 +1,36 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { parseByteSize } from "../src/budget.js"; + +test("KB and MB are decimal (1000), KiB and MiB binary (1024)", () => { + assert.equal(parseByteSize("50KB").bytes, 50000); + assert.equal(parseByteSize("50KiB").bytes, 51200); + assert.equal(parseByteSize("1.5MB").bytes, 1500000); + assert.equal(parseByteSize("2MiB").bytes, 2097152); +}); + +test("a bare number or a B suffix is a byte count", () => { + assert.equal(parseByteSize("48000").bytes, 48000); + assert.equal(parseByteSize("48000B").bytes, 48000); +}); + +test("units are case-insensitive and may be separated by a space", () => { + assert.equal(parseByteSize("50kb").bytes, 50000); + assert.equal(parseByteSize("50 kib").bytes, 51200); +}); + +test("keeps a normalized label of what was asked for", () => { + assert.equal(parseByteSize("50kb").label, "50 KB"); + assert.equal(parseByteSize("50 kib").label, "50 KiB"); + assert.equal(parseByteSize("48000").label, "48000 B"); +}); + +test("rejects unknown units, non-numbers and budgets under one byte", () => { + for (const value of ["50kbit", "fifty KB", "", "0KB", "-5KB", "0.5"]) { + assert.throws(() => parseByteSize(value), /--target-bytes/, `rejects "${value}"`); + } +}); + +test("rounds a fractional byte count down, so the budget is never exceeded", () => { + assert.equal(parseByteSize("1.0005KB").bytes, 1000); +}); diff --git a/compare/test/integration.test.js b/compare/test/integration.test.js index 59da471..862a6b6 100644 --- a/compare/test/integration.test.js +++ b/compare/test/integration.test.js @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { deflateSync } from "node:zlib"; import { CODECS } from "../src/codecs.js"; -import { findQualityForTarget } from "../src/pipeline.js"; +import { findQualityForTarget, findQualityForBudget } from "../src/pipeline.js"; import { sweepCodec } from "../src/sweep.js"; import { writeStrippedPng, pngDimensions } from "../src/image.js"; import { resolveCommand } from "../src/exec.js"; @@ -105,6 +105,42 @@ test("searches WebP quality to a real perceptual target", { skip: webpReady ? fa }); }); +for (const id of ["jxl", "webp"]) { + const codec = CODECS[id]; + const ready = id === "jxl" ? jxlReady : webpReady; + + test(`finds the best ${codec.name} quality that fits a byte budget`, { skip: ready ? false : "codecs not on PATH" }, () => { + withWorkdir((dir) => { + const ref = join(dir, "ref.png"); + makeTestPng(ref, 128, 96); + // A budget halfway between a low and a high quality encode of this image. The + // low one fits, so the search must find a file at least as large and as good. + const low = findQualityForTarget(codec, ref, 40, dir, { maxIterations: 6 }); + const high = findQualityForTarget(codec, ref, 90, dir, { maxIterations: 6 }); + const budget = Math.round((low.bytes + high.bytes) / 2); + + const r = findQualityForBudget(codec, ref, budget, dir, { maxIterations: 10 }); + assert.equal(r.fits, true); + assert.equal(r.budgetBytes, budget); + assert.ok(r.bytes <= budget, `${r.bytes} B fits ${budget} B`); + assert.ok(r.bytes >= low.bytes, `no smaller than a known fit (${low.bytes} B), got ${r.bytes} B`); + assert.ok(r.ssimulacra2 >= low.ssimulacra2 - 0.5, `no worse than a known fit (${low.ssimulacra2}), got ${r.ssimulacra2}`); + assert.equal(readFileSync(join(dir, `${id}.${codec.ext}`)).length, r.bytes, "reports the size of the file it wrote"); + assert.ok(Number.isFinite(r.dssim) && r.bpp > 0); + }); + }); + + test(`reports a ${codec.name} budget it cannot meet instead of a file over it`, { skip: ready ? false : "codecs not on PATH" }, () => { + withWorkdir((dir) => { + const ref = join(dir, "ref.png"); + makeTestPng(ref, 128, 96); + const r = findQualityForBudget(codec, ref, 20, dir, { maxIterations: 6 }); + assert.equal(r.fits, false); + assert.ok(r.bytes > 20 && Number.isFinite(r.ssimulacra2)); + }); + }); +} + test("sweepCodec builds a rate-distortion curve sorted by quality", { skip: jxlReady ? false : "codecs not on PATH" }, () => { withWorkdir((dir) => { const ref = join(dir, "ref.png"); @@ -359,3 +395,45 @@ test("AVIF SVT-AV1 encodes 4:2:0 with libavif's SVT-AV1 encoder", { skip: svtRea assert.equal(r.name, "AVIF SVT-AV1"); }); }); + +test("budget mode compares every codec at the largest file that fits", { skip: jxlReady && webpReady ? false : "codecs not on PATH" }, () => { + withWorkdir((dir) => { + const images = join(dir, "images"); + mkdirSync(images); + makeTestPng(join(images, "a.png"), 128, 96); + makeTestPng(join(images, "b.png"), 96, 128); + const csvPath = join(dir, "budget.csv"); + + const res = spawnSync(process.execPath, [CLI, images, "--target-bytes", "2KiB", "--codecs", "jxl,webp", "--csv", csvPath], { encoding: "utf8" }); + assert.equal(res.status, 0, res.stderr); + assert.match(res.stdout, /Budget: 2 KiB = 2,048 bytes/, "states the budget in each table"); + assert.match(res.stdout, /of budget/); + assert.match(res.stdout, /Budget summary — 2 images/, "prints the batch summary"); + assert.doesNotMatch(res.stdout, /Target: ssimulacra2/, "replaces the equal-quality table"); + + const [header, ...lines] = readFileSync(csvPath, "utf8").trim().split("\n"); + const col = (name) => header.split(",").indexOf(name); + assert.equal(lines.length, 4, "one CSV row per image and codec"); + for (const line of lines) { + const cells = line.split(","); + assert.equal(cells[col("budget_bytes")], "2048"); + if (cells[col("fits")] === "true") assert.ok(Number(cells[col("bytes")]) <= 2048, line); + } + }); +}); + +const runCli = (args) => spawnSync(process.execPath, [CLI, ...args], { encoding: "utf8" }); + +test("budget mode rejects options that belong to another mode, and invalid sizes", () => { + const cases = [ + [["x.png", "--target-bytes", "50KB", "--target", "85"], /--target-bytes and --target/], + [["x.png", "--target-bytes", "50KB", "--rd", "80,90"], /--target-bytes and --rd/], + [["x.png", "--target-bytes", "50KB", "--html", "out.html"], /--html .*--target-bytes/], + [["x.png", "--target-bytes", "50 kbit"], /--target-bytes must be a size/], + ]; + for (const [args, message] of cases) { + const res = runCli(args); + assert.equal(res.status, 1, args.join(" ")); + assert.match(res.stderr, message, args.join(" ")); + } +}); diff --git a/compare/test/report-budget.test.js b/compare/test/report-budget.test.js new file mode 100644 index 0000000..5b47969 --- /dev/null +++ b/compare/test/report-budget.test.js @@ -0,0 +1,119 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { toBudgetTable, toBudgetAggregateTable, toBudgetCsv } from "../src/report.js"; +import { aggregateBudget } from "../src/batch.js"; + +const timing = { encodeWallMs: 410, encodeCpuMs: 1290, totalEncodeWallMs: 1800, totalEncodeCpuMs: 5400, encodePeakBytes: 50331648 }; +const results = [ + { id: "mozjpeg", name: "mozjpeg", label: "-quality 71", bytes: 49870, bpp: 1.52, ssimulacra2: 78.4, dssim: 0.0011, iterations: 7, budgetBytes: 50000, fits: true, ...timing }, + { id: "jxl", name: "JPEG XL", label: "-d 1.2", bytes: 49512, bpp: 1.51, ssimulacra2: 84.9, dssim: 0.0006, iterations: 5, budgetBytes: 50000, fits: true, ...timing }, + { id: "heic", name: "HEIC", label: "-q 1", bytes: 61000, bpp: 1.86, ssimulacra2: 88.0, dssim: 0.0004, iterations: 10, budgetBytes: 50000, fits: false, ...timing }, + { id: "avif", name: "AVIF", failed: true, error: "avifenc exited with 1" }, +]; +const meta = { reference: "photo.png", width: 512, height: 512, budgetBytes: 50000, budgetLabel: "50 KB" }; +const rowOrder = (table, names) => names.map((n) => table.indexOf(`| ${n} `)); + +test("budget table ranks codecs that fit by quality, best first, then the rest", () => { + const table = toBudgetTable(results, meta); + const [jxl, moz, heic, avif] = rowOrder(table, ["JPEG XL", "mozjpeg", "HEIC", "AVIF"]); + assert.ok(jxl < moz, "higher ssimulacra2 first"); + assert.ok(moz < heic, "a codec over the budget ranks after every codec that fits, whatever its score"); + assert.ok(heic < avif, "failed codecs last"); +}); + +test("budget table states the budget in the unit asked for and in bytes", () => { + const table = toBudgetTable(results, meta); + assert.match(table, /photo\.png \(512×512\)/); + assert.match(table, /Budget: 50 KB = 50,000 bytes/); + assert.match(table, /compare quality/); +}); + +test("budget table shows exact sizes and the share of the budget used", () => { + const table = toBudgetTable(results, meta); + assert.match(table, /49,512 B/); + assert.match(table, /99\.0%/, "JPEG XL uses 99.0% of the budget"); + assert.match(table, /122\.0% \*/, "HEIC is over the budget, flagged"); + assert.match(table, /\* cannot fit the budget/); + assert.match(table, /† AVIF failed: avifenc exited with 1/); +}); + +test("budget table uses ASCII borders and keeps the timing columns", () => { + const table = toBudgetTable(results, meta); + assert.match(table, /\+-+\+/); + assert.match(table, /encode .* cpu .* memory/); +}); + +test("budget CSV has one row per image and codec, with the budget and whether it fits", () => { + const csv = toBudgetCsv([{ image: "photo.png", results }]); + const [header, ...rows] = csv.split("\n"); + assert.equal( + header, + "image,codec,setting,budget_bytes,bytes,bpp,ssimulacra2,dssim,fits,iterations," + + "encode_wall_ms,encode_cpu_ms,total_encode_wall_ms,total_encode_cpu_ms,encode_peak_rss_bytes,error", + ); + assert.equal(rows.length, 4); + assert.equal(rows[0], "photo.png,JPEG XL,-d 1.2,50000,49512,1.5100,84.9000,0.000600,true,5,410,1290,1800,5400,50331648,"); + assert.match(rows[2], /^photo\.png,HEIC,-q 1,50000,61000,.*,false,/); + assert.equal(rows[3], "photo.png,AVIF,,,,,,,,,,,,,,avifenc exited with 1"); +}); + +const fit = (id, name, ssimulacra2, fits = true) => ({ id, name, ssimulacra2, fits, bytes: 1, bpp: 1 }); +// HEIC cannot fit a.png; c.png is the hard image where it is the only codec to fit. +const perImage = [ + { image: "a.png", results: [fit("jxl", "JPEG XL", 85), fit("mozjpeg", "mozjpeg", 80), fit("heic", "HEIC", 95, false)] }, + { image: "b.png", results: [fit("jxl", "JPEG XL", 75), fit("mozjpeg", "mozjpeg", 78), fit("heic", "HEIC", 90)] }, + { image: "c.png", results: [fit("jxl", "JPEG XL", 30, false), fit("mozjpeg", "mozjpeg", 20, false), fit("heic", "HEIC", 10)] }, +]; +const byId = (rows) => Object.fromEntries(rows.map((r) => [r.id, r])); + +test("budget aggregate averages quality over the images where every codec fits", () => { + // Only b.png: averaging each codec over its own images would rank them on + // different images, rewarding a codec for not fitting the hard ones. + const rows = byId(aggregateBudget(perImage, { baselineId: "mozjpeg" })); + assert.equal(rows.jxl.avgScore, 75); + assert.equal(rows.mozjpeg.avgScore, 78); + assert.equal(rows.heic.avgScore, 90); + assert.equal(rows.jxl.compared, 1, "names how many images the averages cover"); +}); + +test("budget aggregate compares with the baseline over the same images", () => { + const rows = byId(aggregateBudget(perImage, { baselineId: "mozjpeg" })); + assert.equal(rows.jxl.deltaVsBaseline, -3); + assert.equal(rows.heic.deltaVsBaseline, 12); + assert.equal(rows.mozjpeg.deltaVsBaseline, 0); +}); + +test("budget aggregate counts wins and fits on every image", () => { + const rows = byId(aggregateBudget(perImage, { baselineId: "mozjpeg" })); + assert.deepEqual([rows.jxl.wins, rows.mozjpeg.wins, rows.heic.wins], [1, 0, 2], "a win needs the codec to fit"); + assert.deepEqual([rows.jxl.fits, rows.heic.fits, rows.heic.count], [2, 2, 3]); +}); + +test("budget aggregate is sorted by average quality, best first", () => { + const rows = aggregateBudget(perImage, { baselineId: "mozjpeg" }); + assert.deepEqual(rows.map((r) => r.id), ["heic", "mozjpeg", "jxl"]); +}); + +test("budget aggregate has no averages when no image fits with every codec", () => { + const rows = aggregateBudget([perImage[0], perImage[2]], { baselineId: "mozjpeg" }); + assert.ok(rows.every((r) => r.avgScore === null && r.deltaVsBaseline === null && r.compared === 0)); + assert.deepEqual(byId(rows).heic.wins, 1, "wins still count"); +}); + +test("budget aggregate table names the budget, the baseline and the images compared", () => { + const rows = aggregateBudget(perImage, { baselineId: "mozjpeg" }); + const table = toBudgetAggregateTable(rows, { imageCount: 3, budgetBytes: 50000, budgetLabel: "50 KB", baselineId: "mozjpeg", baselineName: "mozjpeg" }); + assert.match(table, /Budget summary — 3 images, budget 50 KB = 50,000 bytes/); + assert.match(table, /the 1 of 3 images where every codec fits/); + assert.match(table, /avg ssimulacra2/); + assert.match(table, /vs mozjpeg/); + assert.match(table, /\+12\.00/); + assert.match(table, /baseline/); + assert.match(table, /2\/3/, "HEIC fits two of three images"); +}); + +test("budget aggregate table says so when no image fits with every codec", () => { + const rows = aggregateBudget([perImage[0], perImage[2]], { baselineId: "mozjpeg" }); + const table = toBudgetAggregateTable(rows, { imageCount: 2, budgetBytes: 50000, budgetLabel: "50 KB", baselineId: "mozjpeg", baselineName: "mozjpeg" }); + assert.match(table, /No image fits the budget with every codec/); +}); diff --git a/compare/test/search.test.js b/compare/test/search.test.js index 254ca6c..24a1db1 100644 --- a/compare/test/search.test.js +++ b/compare/test/search.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { searchForTarget } from "../src/search.js"; +import { searchForTarget, searchForBudget } from "../src/search.js"; test("converges to the target on an increasing function", () => { // evaluate(x) = x, so the target score equals the value we search for. @@ -60,3 +60,78 @@ test("clamps the target to the achievable range at the bounds", () => { }); assert.ok(result.value <= 100 && result.value >= 99, `value ${result.value}`); }); + +// Budget search: the size grows with quality, so the best setting is the one +// with the largest file that still fits. + +test("budget search returns the largest size that fits", () => { + // bytes(q) = 1000 * q on a 0..100 quality knob; 42,500 bytes fit at q <= 42.5. + const result = searchForBudget({ + lo: 0, + hi: 100, + budget: 42500, + increasing: true, + evaluate: (q) => Math.round(1000 * q), + }); + assert.equal(result.fits, true); + assert.ok(result.bytes <= 42500, `bytes ${result.bytes}`); + assert.ok(result.bytes >= 42500 * 0.99, `within 1% under the budget, got ${result.bytes}`); +}); + +test("budget search handles knobs where a higher value means a smaller file", () => { + // Distance knobs (cjxl -d): bytes fall as the knob rises. + const result = searchForBudget({ + lo: 0, + hi: 100, + budget: 30000, + increasing: false, + evaluate: (d) => Math.round(1000 * (100 - d)), + }); + assert.equal(result.fits, true); + assert.ok(result.bytes <= 30000 && result.bytes >= 29700, `bytes ${result.bytes}`); + assert.ok(Math.abs(result.value - 70) <= 0.5, `value ${result.value}`); +}); + +test("budget search never returns an evaluation over the budget when one fits", () => { + // Coarse steps: every evaluation lands on a multiple of 10,000 bytes, so the + // closest size (50,000) is over the budget and the answer is the 40,000 below it. + const result = searchForBudget({ + lo: 0, + hi: 100, + budget: 49000, + maxIterations: 10, + increasing: true, + evaluate: (q) => Math.round(q / 10) * 10000, + }); + assert.equal(result.fits, true); + assert.equal(result.bytes, 40000); +}); + +test("budget search reports the smallest file when nothing fits", () => { + // Even the lowest quality is 5,000 bytes against a 1,000-byte budget. + const result = searchForBudget({ + lo: 0, + hi: 100, + budget: 1000, + increasing: true, + evaluate: (q) => 5000 + Math.round(100 * q), + }); + assert.equal(result.fits, false); + assert.ok(result.bytes < 5100, `closest to the lowest setting, got ${result.bytes}`); +}); + +test("budget search stops early once within the tolerance under the budget", () => { + let calls = 0; + searchForBudget({ + lo: 0, + hi: 100, + budget: 50000, + tolerance: 1000, + increasing: true, + evaluate: (q) => { + calls += 1; + return Math.round(1000 * q); // the first midpoint, q = 50, is exactly 50,000 + }, + }); + assert.equal(calls, 1); +});