From f008feeacfbb631cd33bb824567794fd8d969a7c Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 14:34:03 +0100 Subject: [PATCH 1/2] tools/fsrbench: the ffmpeg comparison as a cobra command, with tests (#141) A module of its own (cobra v1.10.2, replace to this tree) so the upscale package keeps no dependency. quality and speed subcommands are the harness behind the README tables; its tests run against a fake ffmpeg and taskset and hold 100% coverage, gated in CI. Refs #141 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 27 ++++ README.md | 5 + tools/fsrbench/- | Bin 0 -> 72 bytes tools/fsrbench/go.mod | 16 ++ tools/fsrbench/go.sum | 10 ++ tools/fsrbench/main.go | 260 ++++++++++++++++++++++++++++++ tools/fsrbench/main_test.go | 305 ++++++++++++++++++++++++++++++++++++ 7 files changed, 623 insertions(+) create mode 100644 tools/fsrbench/- create mode 100644 tools/fsrbench/go.mod create mode 100644 tools/fsrbench/go.sum create mode 100644 tools/fsrbench/main.go create mode 100644 tools/fsrbench/main_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6118f97..a7007e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,6 +100,33 @@ jobs: awk -v t="$cov" 'BEGIN { exit !(t+0 >= 100.0) }' || { echo "::error::coverage ${cov}% < 100%"; exit 1; } + # tools/fsrbench is a module of its own (cobra), measuring ./upscale against + # ffmpeg; its tests run against a fake ffmpeg, so no ffmpeg is needed. + fsrbench: + name: tools/fsrbench (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + defaults: + run: + working-directory: tools/fsrbench + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7 + with: + go-version: '1.27.4' + - run: go vet ./... + - name: Test + 100% coverage gate + shell: bash + run: | + go test -race -coverprofile=cover.out ./... + cov=$(go tool cover -func=cover.out | tail -1 | awk '{print $3}' | tr -d '%') + echo "coverage: ${cov}%" + awk -v t="$cov" 'BEGIN { exit !(t+0 >= 100.0) }' || { + echo "::error::coverage ${cov}% < 100%"; exit 1; } + # The media module on 32-bit. A job of its own on Linux, not a step guarded by # `if: runner.os` in the matrix above: buildscan reads that step as a 32-bit # build on every OS of the matrix, including darwin/386, which does not exist. diff --git a/README.md b/README.md index 4500d07..081cf1b 100644 --- a/README.md +++ b/README.md @@ -1437,6 +1437,11 @@ AVX2/AVX-512 and NEON; the scalar build is the default and the two agree within is an open defect (the 12-tap gather per output pixel dominates), so it suits stills, offline work and small frames, not real-time 1080p. +Reproduce both tables with `tools/fsrbench` (its own module; needs `ffmpeg` on the +PATH): `go run ./tools/fsrbench quality --gt in.png --dir ` and +`go run ./tools/fsrbench speed --core 9`; the upscale side of the speed table is +`GOEXPERIMENT=simd go test -bench 720to1080 ./upscale`. + ## Guarantees - **Pure Go, CGO=0.** No `libav`, no `exec` to `ffmpeg`. diff --git a/tools/fsrbench/- b/tools/fsrbench/- new file mode 100644 index 0000000000000000000000000000000000000000..b3fbfc446f144e7ce39d13169080c6261ae56b61 GIT binary patch literal 72 zcmeAS@N?(olHy`uVBq!ia0vp^93afW1|*O0@9PFq{GKk3Ar*6yk`x%+I+zYHa0M_3 UUOQT*1C(O$boFyt=akR{0Mu*`YXATM literal 0 HcmV?d00001 diff --git a/tools/fsrbench/go.mod b/tools/fsrbench/go.mod new file mode 100644 index 0000000..f613d67 --- /dev/null +++ b/tools/fsrbench/go.mod @@ -0,0 +1,16 @@ +module github.com/go-avkit/avkit/tools/fsrbench + +go 1.27.4 + +require ( + github.com/go-avkit/avkit v0.21.0 + github.com/spf13/cobra v1.10.2 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) + +// The tool measures the upscale package of this very tree. +replace github.com/go-avkit/avkit => ../.. diff --git a/tools/fsrbench/go.sum b/tools/fsrbench/go.sum new file mode 100644 index 0000000..a6ee3e0 --- /dev/null +++ b/tools/fsrbench/go.sum @@ -0,0 +1,10 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/tools/fsrbench/main.go b/tools/fsrbench/main.go new file mode 100644 index 0000000..5f2ca27 --- /dev/null +++ b/tools/fsrbench/main.go @@ -0,0 +1,260 @@ +// Command fsrbench measures the upscale package against ffmpeg's scaler, so +// that the numbers in the README can be reproduced. +// +// fsrbench quality --gt in.png --dir workdir [--w 1920 --h 1080 --factor 2] +// fsrbench speed [--w 1280 --h 720 --ow 1920 --oh 1080 --frames 300 --core 9] +// +// quality: the ground truth is scaled to w x h with ffmpeg's area filter, +// downscaled by factor with the same filter, then upscaled back by each +// method; PSNR (mean of R, G, B) and SSIM (all planes) are read from +// ffmpeg's own psnr and ssim filters against the ground truth. +// +// speed: user CPU time per frame of ffmpeg's scale filter on a single +// thread, with the cost of the source and of the pipeline subtracted. The +// upscale side is measured by `go test -bench 720to1080 ./upscale`. +package main + +import ( + "fmt" + "image" + "image/png" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + + "github.com/go-avkit/avkit/upscale" + "github.com/spf13/cobra" +) + +var osExit = os.Exit + +func main() { + if err := RootCmd().Execute(); err != nil { + osExit(1) + } +} + +// RootCmd builds the command tree. +func RootCmd() *cobra.Command { + root := &cobra.Command{ + Use: "fsrbench", + Short: "Measure the upscale package against ffmpeg's scaler", + SilenceUsage: true, + SilenceErrors: false, + } + root.AddCommand(qualityCmd(), speedCmd()) + return root +} + +var ( + psnrRE = regexp.MustCompile(`PSNR r:([0-9.]+|inf) g:([0-9.]+|inf) b:([0-9.]+|inf)`) + ssimRE = regexp.MustCompile(`SSIM R:[0-9.]+ \([0-9.]+\) G:[0-9.]+ \([0-9.]+\) B:[0-9.]+ \([0-9.]+\) All:([0-9.]+)`) + benchRE = regexp.MustCompile(`bench: utime=([0-9.]+)s`) + infValue = 100.0 +) + +// parseQuality extracts mean PSNR (dB, inf capped at 100) and SSIM from the +// stderr of ffmpeg's psnr and ssim filters. +func parseQuality(s string) (psnr, ssim float64, err error) { + m := psnrRE.FindStringSubmatch(s) + k := ssimRE.FindStringSubmatch(s) + if m == nil || k == nil { + return 0, 0, fmt.Errorf("no psnr/ssim in ffmpeg output") + } + for _, v := range m[1:] { + f := infValue + if v != "inf" { + if f, err = strconv.ParseFloat(v, 64); err != nil { + return 0, 0, err + } + } + psnr += f / 3 + } + ssim, err = strconv.ParseFloat(k[1], 64) + return psnr, ssim, err +} + +// parseUtime extracts the user CPU seconds from ffmpeg -benchmark. +func parseUtime(s string) (float64, error) { + m := benchRE.FindStringSubmatch(s) + if m == nil { + return 0, fmt.Errorf("no bench line in ffmpeg output") + } + return strconv.ParseFloat(m[1], 64) +} + +func ffmpeg(args ...string) (string, error) { + cmd := exec.Command("ffmpeg", append([]string{"-hide_banner", "-nostdin", "-y"}, args...)...) + b, err := cmd.CombinedOutput() + if err != nil { + return string(b), fmt.Errorf("ffmpeg %v: %w\n%s", args, err, b) + } + return string(b), nil +} + +func qualityCmd() *cobra.Command { + var gt, dir string + var w, h int + var factor float64 + c := &cobra.Command{ + Use: "quality", + Short: "PSNR and SSIM of ffmpeg's scalers and of FSR against a ground truth", + SilenceUsage: true, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return quality(cmd, gt, dir, w, h, factor) + }, + } + f := c.Flags() + f.StringVar(>, "gt", "", "ground-truth image (PNG)") + f.StringVar(&dir, "dir", "", "work directory (durable, outside any repository)") + f.IntVar(&w, "w", 1920, "ground-truth width after area scaling") + f.IntVar(&h, "h", 1080, "ground-truth height after area scaling") + f.Float64Var(&factor, "factor", 2, "downscale then upscale factor, 1..4") + return c +} + +func quality(cmd *cobra.Command, gt, dir string, w, h int, factor float64) error { + if gt == "" || dir == "" { + return fmt.Errorf("--gt and --dir are required") + } + if factor < 1 || factor > 4 { + return fmt.Errorf("factor %v outside 1..4", factor) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + p := func(n string) string { return filepath.Join(dir, n) } + iw, ih := int(float64(w)/factor), int(float64(h)/factor) + if _, err := ffmpeg("-i", gt, "-frames:v", "1", "-vf", fmt.Sprintf("scale=%d:%d:flags=area,format=rgb24", w, h), p("gt.png")); err != nil { + return err + } + if _, err := ffmpeg("-i", p("gt.png"), "-vf", fmt.Sprintf("scale=%d:%d:flags=area,format=rgb24", iw, ih), p("low.png")); err != nil { + return err + } + f, err := os.Open(p("low.png")) + if err != nil { + return err + } + low, err := png.Decode(f) + f.Close() + if err != nil { + return err + } + type row struct{ name, file string } + var rows []row + for _, m := range []string{"bilinear", "bicubic", "lanczos"} { + if _, err := ffmpeg("-i", p("low.png"), "-vf", fmt.Sprintf("scale=%d:%d:flags=%s,format=rgb24", w, h, m), p(m+".png")); err != nil { + return err + } + rows = append(rows, row{"ffmpeg " + m, p(m + ".png")}) + } + for _, v := range []struct { + name string + sharp float32 + }{{"FSR EASU only", -1}, {"FSR EASU+RCAS 0.2", 0.2}, {"FSR EASU+RCAS 0.0", 0}} { + up, err := upscale.Upscale(low, w, h, &upscale.Options{Sharpness: v.sharp}) + if err != nil { + return err + } + fn := p(fmt.Sprintf("fsr%v.png", v.sharp)) + if err := writePNG(fn, up); err != nil { + return err + } + rows = append(rows, row{v.name, fn}) + } + out := cmd.OutOrStdout() + fmt.Fprintf(out, "ground truth %s -> %dx%d, low %dx%d, back x%g\n\n| method | PSNR dB | SSIM |\n|---|---|---|\n", filepath.Base(gt), w, h, iw, ih, factor) + for _, r := range rows { + o, err := ffmpeg("-i", r.file, "-i", p("gt.png"), "-lavfi", "[0:v][1:v]psnr;[0:v][1:v]ssim", "-f", "null", "-") + if err != nil { + return err + } + ps, ss, err := parseQuality(o) + if err != nil { + return err + } + fmt.Fprintf(out, "| %s | %.2f | %.4f |\n", r.name, ps, ss) + } + return nil +} + +func writePNG(fn string, m image.Image) error { + f, err := os.Create(fn) + if err != nil { + return err + } + if err := png.Encode(f, m); err != nil { + f.Close() + return err + } + return f.Close() +} + +func speedCmd() *cobra.Command { + var w, h, ow, oh, frames, core, rounds int + c := &cobra.Command{ + Use: "speed", + Short: "ms per frame of ffmpeg's scale filter, one thread", + SilenceUsage: true, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if frames < 1 || rounds < 1 { + return fmt.Errorf("--frames and --rounds must be positive") + } + return speed(cmd, w, h, ow, oh, frames, core, rounds) + }, + } + f := c.Flags() + f.IntVar(&w, "w", 1280, "input width") + f.IntVar(&h, "h", 720, "input height") + f.IntVar(&ow, "ow", 1920, "output width") + f.IntVar(&oh, "oh", 1080, "output height") + f.IntVar(&frames, "frames", 300, "frames") + f.IntVar(&core, "core", -1, "pin to this core with taskset (Linux), -1 for none") + f.IntVar(&rounds, "rounds", 5, "interleaved rounds") + return c +} + +func speed(cmd *cobra.Command, w, h, ow, oh, frames, core, rounds int) error { + run := func(vf string) (float64, error) { + a := []string{"-benchmark", "-threads", "1", "-filter_threads", "1", "-f", "lavfi", "-i", + fmt.Sprintf("testsrc2=size=%dx%d:rate=60", w, h), "-frames:v", strconv.Itoa(frames), "-vf", vf, "-f", "null", "-"} + name, argv := "ffmpeg", append([]string{"-hide_banner", "-nostdin"}, a...) + if core >= 0 { + name, argv = "taskset", append([]string{"-c", strconv.Itoa(core), "ffmpeg"}, argv...) + } + b, err := exec.Command(name, argv...).CombinedOutput() + if err != nil { + return 0, fmt.Errorf("%v: %w\n%s", argv, err, b) + } + return parseUtime(string(b)) + } + type cfg struct{ name, vf string } + base := cfg{"base", "format=rgba"} + cfgs := []cfg{ + {"bilinear", fmt.Sprintf("scale=%d:%d:flags=bilinear,format=rgba", ow, oh)}, + {"bicubic", fmt.Sprintf("scale=%d:%d:flags=bicubic,format=rgba", ow, oh)}, + {"lanczos", fmt.Sprintf("scale=%d:%d:flags=lanczos,format=rgba", ow, oh)}, + } + best := map[string]float64{} + for r := 0; r < rounds; r++ { + for _, c := range append([]cfg{base}, cfgs...) { + t, err := run(c.vf) + if err != nil { + return err + } + if b, ok := best[c.name]; !ok || t < b { + best[c.name] = t + } + } + } + out := cmd.OutOrStdout() + fmt.Fprintf(out, "ffmpeg scale %dx%d -> %dx%d, rgba out, 1 thread, best of %d, ms/frame (utime minus source and conversion):\n", w, h, ow, oh, rounds) + for _, c := range cfgs { + fmt.Fprintf(out, "%s\t%.2f\n", c.name, 1000*(best[c.name]-best["base"])/float64(frames)) + } + return nil +} diff --git a/tools/fsrbench/main_test.go b/tools/fsrbench/main_test.go new file mode 100644 index 0000000..5194eac --- /dev/null +++ b/tools/fsrbench/main_test.go @@ -0,0 +1,305 @@ +//go:build !windows + +package main + +import ( + "bytes" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +func TestParseQuality(t *testing.T) { + s := "[Parsed_psnr_0] PSNR r:30.0 g:31.5 b:inf average:40 min:1 max:2\n" + + "[Parsed_ssim_1] SSIM R:0.98 (17.0) G:0.97 (15.0) B:0.96 (14.0) All:0.970000 (15.2)\n" + p, k, err := parseQuality(s) + if err != nil { + t.Fatal(err) + } + if want := (30.0 + 31.5 + 100) / 3; p < want-1e-9 || p > want+1e-9 { + t.Errorf("psnr %v want %v", p, want) + } + if k != 0.97 { + t.Errorf("ssim %v", k) + } + if _, _, err := parseQuality("nothing"); err == nil { + t.Error("garbage accepted") + } + if _, _, err := parseQuality("PSNR r:1.2.3 g:1 b:1\nSSIM R:0.9 (1.0) G:0.9 (1.0) B:0.9 (1.0) All:0.9"); err == nil { + t.Error("malformed psnr accepted") + } +} + +func TestParseUtime(t *testing.T) { + v, err := parseUtime("frame= 3\nbench: utime=1.250s\nbench: maxrss=1") + if err != nil || v != 1.25 { + t.Fatalf("%v %v", v, err) + } + if _, err := parseUtime("x"); err == nil { + t.Error("garbage accepted") + } +} + +// fakeBin installs a fake ffmpeg and taskset first on PATH. ffmpeg answers +// -benchmark with a utime of 2 s for a scale filter and 1 s without; a psnr +// filter with the two quality lines; anything else copies the PNG fixture to +// its last argument. taskset drops "-c N" and runs the rest. +func fakeBin(t *testing.T) { + t.Helper() + dir := t.TempDir() + fix := filepath.Join(dir, "fixture.png") + img := image.NewRGBA(image.Rect(0, 0, 8, 8)) + for i := range img.Pix { + img.Pix[i] = uint8(i * 7) + } + img.Set(1, 1, color.RGBA{255, 0, 0, 255}) + f, err := os.Create(fix) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, img); err != nil { + t.Fatal(err) + } + f.Close() + ffm := `#!/bin/sh +all="$*" +for a; do last="$a"; done +case "$all" in +*-benchmark*) + case "$all" in + *scale=*) echo "bench: utime=2.000s";; + *) echo "bench: utime=1.000s";; + esac;; +*psnr*) + echo "PSNR r:30.0 g:31.0 b:32.0 average:31" + echo "SSIM R:0.9 (10.0) G:0.9 (10.0) B:0.9 (10.0) All:0.900000 (10.0)";; +*) cp "` + fix + `" "$last";; +esac +` + ts := "#!/bin/sh\nshift 2\nexec \"$@\"\n" + for n, s := range map[string]string{"ffmpeg": ffm, "taskset": ts} { + if err := os.WriteFile(filepath.Join(dir, n), []byte(s), 0o755); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func runCmd(t *testing.T, args ...string) (string, error) { + t.Helper() + var out, errb bytes.Buffer + c := RootCmd() + c.SetOut(&out) + c.SetErr(&errb) + c.SetArgs(args) + err := c.Execute() + return out.String(), err +} + +func TestQuality(t *testing.T) { + fakeBin(t) + dir := filepath.Join(t.TempDir(), "work") + out, err := runCmd(t, "quality", "--gt", "in.png", "--dir", dir, "--w", "8", "--h", "8", "--factor", "2") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"ground truth in.png -> 8x8, low 4x4, back x2", "| ffmpeg lanczos | 31.00 | 0.9000 |", "| FSR EASU only |", "| FSR EASU+RCAS 0.2 |", "| FSR EASU+RCAS 0.0 |"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in\n%s", want, out) + } + } + for _, n := range []string{"gt.png", "low.png", "bilinear.png", "fsr-1.png", "fsr0.2.png", "fsr0.png"} { + if _, err := os.Stat(filepath.Join(dir, n)); err != nil { + t.Error(err) + } + } +} + +func TestQualityRefusals(t *testing.T) { + fakeBin(t) + for _, a := range [][]string{ + {"quality"}, + {"quality", "--gt", "x"}, + {"quality", "--dir", "y"}, + {"quality", "--gt", "x", "--dir", "y", "--factor", "9"}, + {"quality", "--gt", "x", "--dir", "y", "--factor", "0.5"}, + {"quality", "extra"}, + {"bogus"}, + } { + if _, err := runCmd(t, a...); err == nil { + t.Errorf("%v accepted", a) + } + } + // A work directory under a regular file cannot be created. + f := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(f, nil, 0o644); err != nil { + t.Fatal(err) + } + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(f, "d")); err == nil { + t.Error("unwritable dir accepted") + } + // factor bounds are inclusive. + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(t.TempDir(), "a"), "--w", "8", "--h", "8", "--factor", "1"); err != nil { + t.Errorf("factor 1: %v", err) + } + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(t.TempDir(), "b"), "--w", "16", "--h", "16", "--factor", "4"); err != nil { + t.Errorf("factor 4: %v", err) + } +} + +func TestQualityFFmpegFailures(t *testing.T) { + // No ffmpeg at all. + t.Setenv("PATH", t.TempDir()) + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", t.TempDir()); err == nil { + t.Error("missing ffmpeg accepted") + } + if _, err := runCmd(t, "speed", "--rounds", "1"); err == nil { + t.Error("missing ffmpeg accepted by speed") + } + // An ffmpeg that fails at its nth call: 2 + 3 conversions, 6 measures. + dir := t.TempDir() + fixture := filepath.Join(dir, "fixture.png") + fx, err := os.Create(fixture) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(fx, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil { + t.Fatal(err) + } + fx.Close() + cnt := filepath.Join(dir, "n") + script := "#!/bin/sh\nn=$(cat '" + cnt + "' 2>/dev/null || echo 0)\nn=$((n+1))\necho $n > '" + cnt + "'\n" + + "[ \"$n\" = \"$FAILAT\" ] && exit 1\nfor a; do last=\"$a\"; done\ncp \"$FIXTURE\" \"$last\" 2>/dev/null\necho 'PSNR r:1 g:1 b:1'\nexit 0\n" + if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+"/bin:/usr/bin") + t.Setenv("FIXTURE", fixture) + for at := 1; at <= 11; at++ { + os.Remove(cnt) + t.Setenv("FAILAT", strconv.Itoa(at)) + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"+strconv.Itoa(at)), "--w", "16", "--h", "16"); err == nil { + t.Errorf("failure at call %d accepted", at) + } + } + // An upscale refusal (zero width) and an unwritable result file. + os.Remove(cnt) + t.Setenv("FAILAT", "0") + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "z"), "--w", "0", "--h", "16"); err == nil { + t.Error("zero width accepted") + } + os.Remove(cnt) + blocked := filepath.Join(dir, "blocked") + if err := os.MkdirAll(filepath.Join(blocked, "fsr-1.png"), 0o755); err != nil { + t.Fatal(err) + } + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", blocked, "--w", "16", "--h", "16"); err == nil { + t.Error("unwritable result accepted") + } +} + +func TestQualityBadLow(t *testing.T) { + // ffmpeg "succeeds" but writes something that is not a PNG. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte("#!/bin/sh\nfor a; do last=\"$a\"; done\necho junk > \"$last\"\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w")); err == nil { + t.Error("non-PNG low image accepted") + } + // ffmpeg "succeeds" and writes nothing: the low image cannot be opened. + if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatal(err) + } + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "v")); err == nil { + t.Error("missing low image accepted") + } +} + +func TestQualityNoMetrics(t *testing.T) { + fakeBin(t) + // Replace the fake psnr answer by nothing parsable. + dir := t.TempDir() + fix := filepath.Join(t.TempDir(), "f.png") + img := image.NewRGBA(image.Rect(0, 0, 4, 4)) + f, _ := os.Create(fix) + if err := png.Encode(f, img); err != nil { + t.Fatal(err) + } + f.Close() + s := "#!/bin/sh\nfor a; do last=\"$a\"; done\ncase \"$*\" in *psnr*) echo none;; *) cp '" + fix + "' \"$last\";; esac\n" + if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte(s), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"), "--w", "8", "--h", "8"); err == nil { + t.Error("output without metrics accepted") + } +} + +func TestSpeed(t *testing.T) { + fakeBin(t) + out, err := runCmd(t, "speed", "--frames", "100", "--rounds", "2") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "1280x720 -> 1920x1080") || !strings.Contains(out, "best of 2") { + t.Errorf("header: %s", out) + } + // (2 s - 1 s) / 100 frames = 10 ms. + for _, m := range []string{"bilinear", "bicubic", "lanczos"} { + if !strings.Contains(out, m+"\t10.00\n") { + t.Errorf("%s not 10.00 ms in\n%s", m, out) + } + } + out, err = runCmd(t, "speed", "--frames", "100", "--rounds", "1", "--core", "3") + if err != nil || !strings.Contains(out, "lanczos\t10.00") { + t.Errorf("taskset path: %v %s", err, out) + } +} + +func TestSpeedRefusals(t *testing.T) { + fakeBin(t) + for _, a := range [][]string{{"speed", "--frames", "0"}, {"speed", "--rounds", "0"}, {"speed", "x"}} { + if _, err := runCmd(t, a...); err == nil { + t.Errorf("%v accepted", a) + } + } + // ffmpeg that prints no bench line. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte("#!/bin/sh\necho hi\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + if _, err := runCmd(t, "speed", "--rounds", "1"); err == nil { + t.Error("missing bench line accepted") + } +} + +func TestWritePNGFailures(t *testing.T) { + if err := writePNG(filepath.Join(t.TempDir(), "no", "x.png"), image.NewRGBA(image.Rect(0, 0, 1, 1))); err == nil { + t.Error("missing dir accepted") + } + if err := writePNG(filepath.Join(t.TempDir(), "x.png"), image.NewRGBA(image.Rect(0, 0, 0, 0))); err == nil { + t.Error("empty image accepted") + } +} + +func TestMain_(t *testing.T) { + code := -1 + osExit = func(c int) { code = c } + defer func() { osExit = os.Exit }() + old := os.Args + defer func() { os.Args = old }() + os.Args = []string{"fsrbench", "bogus"} + main() + if code != 1 { + t.Errorf("exit %d", code) + } +} From aa4226dfa10605e4251e2fba7997728fdb2b7ddb Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 14:36:54 +0100 Subject: [PATCH 2/2] tools/fsrbench: tests assert the reason of each refusal Co-Authored-By: Claude Sonnet 5.5 --- tools/fsrbench/main_test.go | 106 ++++++++++++++++++++---------------- 1 file changed, 60 insertions(+), 46 deletions(-) diff --git a/tools/fsrbench/main_test.go b/tools/fsrbench/main_test.go index 5194eac..3a16cfa 100644 --- a/tools/fsrbench/main_test.go +++ b/tools/fsrbench/main_test.go @@ -120,29 +120,38 @@ func TestQuality(t *testing.T) { } } +// wantErr fails unless err holds the text: a guard must fail for ITS reason. +func wantErr(t *testing.T, args []string, err error, want string) { + t.Helper() + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%v: error %v, want one holding %q", args, err, want) + } +} + func TestQualityRefusals(t *testing.T) { fakeBin(t) - for _, a := range [][]string{ - {"quality"}, - {"quality", "--gt", "x"}, - {"quality", "--dir", "y"}, - {"quality", "--gt", "x", "--dir", "y", "--factor", "9"}, - {"quality", "--gt", "x", "--dir", "y", "--factor", "0.5"}, - {"quality", "extra"}, - {"bogus"}, + for _, c := range []struct { + args []string + want string + }{ + {[]string{"quality"}, "--gt and --dir are required"}, + {[]string{"quality", "--gt", "x"}, "--gt and --dir are required"}, + {[]string{"quality", "--dir", "y"}, "--gt and --dir are required"}, + {[]string{"quality", "--gt", "x", "--dir", "y", "--factor", "9"}, "outside 1..4"}, + {[]string{"quality", "--gt", "x", "--dir", "y", "--factor", "0.5"}, "outside 1..4"}, + {[]string{"quality", "extra"}, "unknown command"}, + {[]string{"bogus"}, "unknown command"}, } { - if _, err := runCmd(t, a...); err == nil { - t.Errorf("%v accepted", a) - } + _, err := runCmd(t, c.args...) + wantErr(t, c.args, err, c.want) } // A work directory under a regular file cannot be created. f := filepath.Join(t.TempDir(), "file") if err := os.WriteFile(f, nil, 0o644); err != nil { t.Fatal(err) } - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(f, "d")); err == nil { - t.Error("unwritable dir accepted") - } + _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(f, "d")) + wantErr(t, nil, err, "not a directory") // factor bounds are inclusive. if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(t.TempDir(), "a"), "--w", "8", "--h", "8", "--factor", "1"); err != nil { t.Errorf("factor 1: %v", err) @@ -155,12 +164,10 @@ func TestQualityRefusals(t *testing.T) { func TestQualityFFmpegFailures(t *testing.T) { // No ffmpeg at all. t.Setenv("PATH", t.TempDir()) - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", t.TempDir()); err == nil { - t.Error("missing ffmpeg accepted") - } - if _, err := runCmd(t, "speed", "--rounds", "1"); err == nil { - t.Error("missing ffmpeg accepted by speed") - } + _, err := runCmd(t, "quality", "--gt", "x", "--dir", t.TempDir()) + wantErr(t, nil, err, "executable file not found") + _, err = runCmd(t, "speed", "--rounds", "1") + wantErr(t, nil, err, "executable file not found") // An ffmpeg that fails at its nth call: 2 + 3 conversions, 6 measures. dir := t.TempDir() fixture := filepath.Join(dir, "fixture.png") @@ -168,13 +175,16 @@ func TestQualityFFmpegFailures(t *testing.T) { if err != nil { t.Fatal(err) } + // Every ffmpeg call answers with the metrics lines, so the call that is + // made to fail is the only thing that can stop the run. if err := png.Encode(fx, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil { t.Fatal(err) } fx.Close() cnt := filepath.Join(dir, "n") script := "#!/bin/sh\nn=$(cat '" + cnt + "' 2>/dev/null || echo 0)\nn=$((n+1))\necho $n > '" + cnt + "'\n" + - "[ \"$n\" = \"$FAILAT\" ] && exit 1\nfor a; do last=\"$a\"; done\ncp \"$FIXTURE\" \"$last\" 2>/dev/null\necho 'PSNR r:1 g:1 b:1'\nexit 0\n" + "[ \"$n\" = \"$FAILAT\" ] && { echo \"FAILED-$n\" >&2; exit 1; }\nfor a; do last=\"$a\"; done\ncp \"$FIXTURE\" \"$last\" 2>/dev/null\n" + + "echo 'PSNR r:1 g:1 b:1'\necho 'SSIM R:0.9 (1.0) G:0.9 (1.0) B:0.9 (1.0) All:0.9'\nexit 0\n" if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte(script), 0o755); err != nil { t.Fatal(err) } @@ -183,23 +193,25 @@ func TestQualityFFmpegFailures(t *testing.T) { for at := 1; at <= 11; at++ { os.Remove(cnt) t.Setenv("FAILAT", strconv.Itoa(at)) - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"+strconv.Itoa(at)), "--w", "16", "--h", "16"); err == nil { - t.Errorf("failure at call %d accepted", at) - } + _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"+strconv.Itoa(at)), "--w", "16", "--h", "16") + wantErr(t, nil, err, "FAILED-"+strconv.Itoa(at)) } // An upscale refusal (zero width) and an unwritable result file. os.Remove(cnt) t.Setenv("FAILAT", "0") - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "z"), "--w", "0", "--h", "16"); err == nil { - t.Error("zero width accepted") - } + _, err = runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "z"), "--w", "0", "--h", "16") + wantErr(t, nil, err, "upscale") os.Remove(cnt) blocked := filepath.Join(dir, "blocked") if err := os.MkdirAll(filepath.Join(blocked, "fsr-1.png"), 0o755); err != nil { t.Fatal(err) } - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", blocked, "--w", "16", "--h", "16"); err == nil { - t.Error("unwritable result accepted") + _, err = runCmd(t, "quality", "--gt", "x", "--dir", blocked, "--w", "16", "--h", "16") + wantErr(t, nil, err, "fsr-1.png") + // The metrics of a run that does not fail parse, so nothing above stopped on them. + os.Remove(cnt) + if _, err = runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "ok"), "--w", "16", "--h", "16"); err != nil { + t.Errorf("clean run: %v", err) } } @@ -210,16 +222,14 @@ func TestQualityBadLow(t *testing.T) { t.Fatal(err) } t.Setenv("PATH", dir) - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w")); err == nil { - t.Error("non-PNG low image accepted") - } + _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w")) + wantErr(t, nil, err, "unexpected EOF") // ffmpeg "succeeds" and writes nothing: the low image cannot be opened. if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { t.Fatal(err) } - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "v")); err == nil { - t.Error("missing low image accepted") - } + _, err = runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "v")) + wantErr(t, nil, err, "low.png") } func TestQualityNoMetrics(t *testing.T) { @@ -237,10 +247,9 @@ func TestQualityNoMetrics(t *testing.T) { if err := os.WriteFile(filepath.Join(dir, "ffmpeg"), []byte(s), 0o755); err != nil { t.Fatal(err) } - t.Setenv("PATH", dir) - if _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"), "--w", "8", "--h", "8"); err == nil { - t.Error("output without metrics accepted") - } + t.Setenv("PATH", dir+string(os.PathListSeparator)+"/bin:/usr/bin") + _, err := runCmd(t, "quality", "--gt", "x", "--dir", filepath.Join(dir, "w"), "--w", "8", "--h", "8") + wantErr(t, nil, err, "no psnr/ssim") } func TestSpeed(t *testing.T) { @@ -266,10 +275,16 @@ func TestSpeed(t *testing.T) { func TestSpeedRefusals(t *testing.T) { fakeBin(t) - for _, a := range [][]string{{"speed", "--frames", "0"}, {"speed", "--rounds", "0"}, {"speed", "x"}} { - if _, err := runCmd(t, a...); err == nil { - t.Errorf("%v accepted", a) - } + for _, c := range []struct { + args []string + want string + }{ + {[]string{"speed", "--frames", "0"}, "must be positive"}, + {[]string{"speed", "--rounds", "0"}, "must be positive"}, + {[]string{"speed", "x"}, "unknown command"}, + } { + _, err := runCmd(t, c.args...) + wantErr(t, c.args, err, c.want) } // ffmpeg that prints no bench line. dir := t.TempDir() @@ -277,9 +292,8 @@ func TestSpeedRefusals(t *testing.T) { t.Fatal(err) } t.Setenv("PATH", dir) - if _, err := runCmd(t, "speed", "--rounds", "1"); err == nil { - t.Error("missing bench line accepted") - } + _, err := runCmd(t, "speed", "--rounds", "1") + wantErr(t, nil, err, "no bench line") } func TestWritePNGFailures(t *testing.T) {