Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <workdir>` 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`.
Expand Down
Binary file added tools/fsrbench/-
Binary file not shown.
16 changes: 16 additions & 0 deletions tools/fsrbench/go.mod
Original file line number Diff line number Diff line change
@@ -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 => ../..
10 changes: 10 additions & 0 deletions tools/fsrbench/go.sum
Original file line number Diff line number Diff line change
@@ -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=
260 changes: 260 additions & 0 deletions tools/fsrbench/main.go
Original file line number Diff line number Diff line change
@@ -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, "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
}
Loading
Loading