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
77 changes: 59 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1409,9 +1409,17 @@ checked before allocation (`MaxSourcePixels`, `MaxOutputPixels`,
`MaxDimension`); downscaling is refused.

Accuracy: against a float64 transliteration of the reference (same integer-trick
approximations), the float32 pipeline stays within `ErrorBound` = 2e-4 on a 0..1
scale (measured 2.7e-5 over 662 520 samples without FMA contraction, up to 1.1e-4
where the compiler fuses multiply-adds).
approximations, public as `upscale/fsrref`), the float32 pipeline stays within
`ErrorBound` = 2e-4 on a 0..1 scale on the corpus of `TestOracle` (measured
5.7e-6 at worst over 662 520 samples on arm64, scalar and NEON). The bound does
not hold everywhere: on noise of at most 3 levels of 255, about 0.9 % of the
samples are outside it, by up to 4.7e-3, under the local colour range
(`TestOracleLowContrast`; the cause is not established). Since v0.25.0 the
position of an output pixel in the source is computed in integers, in the
package and in the oracle: computed in floats it fell on an integer for ratios
such as 640 to 1920, where float32 and float64 floors chose footprints one
pixel apart and a saturated edge differed by 0.064 (`TestPhaseTies`). Pixels at
those positions therefore differ from v0.24.0.

Quality, measured with ffmpeg 6.1.1's `psnr` and `ssim` filters. Ground truth is a
real frame, scaled with ffmpeg `area`, downscaled by the factor, and upscaled back
Expand All @@ -1428,23 +1436,56 @@ real frame, scaled with ffmpeg `area`, downscaled by the factor, and upscaled ba
FSR has the highest SSIM on four of five sources; lanczos is slightly ahead on
PSNR on some.

Speed, one core of a Ryzen 9 7950X (load about 2), 1280x720 to 1920x1080, ms per
frame: ffmpeg 6.1.1 `scale` bilinear 3.3, bicubic 2.0, lanczos 2.8 (source and
conversion subtracted) against `upscale` 242 scalar (EASU alone 193) and **37 with
`GOEXPERIMENT=simd`** (EASU alone 28; 55 and 44 at v0.23.0, 82 and 73 before), the portable Go
1.27 `simd` package on AVX2/AVX-512 and NEON; the scalar build is the default and
the two agree within `ErrorBound`. v0.23.0 gathers each source row's taps once,
computes the edge analysis once per source pixel and packs RGBA with vectors;
v0.24.0 gathers with AVX-512 permutes, converts YCbCr inline and hoists the
per-row broadcasts. Still about 13 times slower than ffmpeg's hand-written scaler, which is an open
defect (what is left: the scalar gather, the input conversion and the EASU
arithmetic, in roughly equal shares), so it suits stills, offline work and small
frames, not real-time 1080p.
For a stream of frames, `upscale.NewScaler(opt)` returns a `Scaler` whose
`Upscale(dst, src)` writes into an `*image.RGBA` the caller owns and, once warm,
allocates nothing per frame while the size, the kind and the opacity of the
frames stay the same (a `dst` whose buffer does not hold its rectangle is
refused with `ErrDst`). `Options.Workers` splits the frame into bands of
rows, one goroutine each (0 = `GOMAXPROCS`, at most `MaxWorkers`); the bytes are
those of one worker, whatever the count (`TestWorkersSameBytes`). The float64
oracle the bound is asserted against is public, in `upscale/fsrref`.

Speed on a Ryzen 9 7950X (16 cores, load 1 to 4), 1280x720 YCbCr 4:2:0 to
1920x1080 RGBA, sharpness 0.2, `GOEXPERIMENT=simd` (AVX-512), ms per frame.
`upscale` is the `Scaler`, input conversion and RGBA packing included; ffmpeg
6.1.1 is `scale=...:flags=lanczos`, source and conversion subtracted, so the
comparison favours ffmpeg:

| Threads | `upscale` FSR EASU+RCAS | ffmpeg lanczos |
|---------|-------------------------|----------------|
| 1 | 26.2 (core 9) | 2.8 (core 9) |
| 2 | 13.2 | |
| 4 | 6.9 | |
| 8 | 4.3 to 4.6 | 0.20 |
| 16 | 3.5 to 3.6 | 0.20 |

The `upscale` column is elapsed time per frame throughout (`go test -bench`,
25.8 with one worker when not pinned). For ffmpeg, one thread is user CPU time
on a pinned core; several threads are elapsed time (`-threads 0 -filter_threads
N` and swscale `threads=N`), a difference of two runs of about 0.1 s over 300
frames, so 0.20 is an order of magnitude, not a precise figure. Runs on several
threads used the CPU list `0-12,14-28,30,31`. On one core `upscale` was 37 at
v0.24.0, 55 at v0.23.0 and 82 before; the scalar build, which is the default and
agrees with the vector one within `ErrorBound`, was 242 at v0.24.0. This release
resolves the taps once per output row, factors the rotation out of the twelve
tap offsets and vectorises the luma and the last pixels of an RCAS row.

FSR remains 9.4 times slower than ffmpeg's lanczos on one core and about 17
times on sixteen threads. We do not expect that gap to close on a CPU: a
separable filter applies fixed taps along each axis, where EASU computes for
every output pixel an edge direction from twelve taps, then twelve rotated,
anisotropic weights and a division. A 16-bit integer or half-float path was
considered and not built: by our reasoning, not by measurement, it cannot hold
`ErrorBound` = 2e-4, a 16-bit half-float carrying 11 significant bits. With 16
workers a 1080p frame takes 3.5 ms, which fits a 60 Hz frame (16.7 ms); on one
core it does not. Scaling is 7.4 times at 16 workers and 6 times at 8; where the
rest goes has not been profiled.

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`.
PATH): `go run ./tools/fsrbench quality --gt in.png --dir <workdir>`,
`go run ./tools/fsrbench speed --core 9` and
`go run ./tools/fsrbench speed --threads 16 --cpus 0-12,14-28,30,31`; the upscale side of
the speed table is `GOEXPERIMENT=simd go test -bench 720to1080 ./upscale`.

## Guarantees

Expand Down
56 changes: 41 additions & 15 deletions tools/fsrbench/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
// 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
// thread, with the cost of the source and of the pipeline subtracted. With
// --threads N above 1, ffmpeg runs with -threads 0 -filter_threads N and
// swscale with threads=N, and the elapsed time is measured instead, the CPU
// time being the sum over the threads; --cpus pins the run to a CPU list. The
// upscale side is measured by `go test -bench 720to1080 ./upscale`.
package main

Expand Down Expand Up @@ -52,6 +55,7 @@ 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`)
rtimeRE = regexp.MustCompile(`bench: utime=\S+ stime=\S+ rtime=([0-9.]+)s`)
infValue = 100.0
)

Expand Down Expand Up @@ -85,6 +89,16 @@ func parseUtime(s string) (float64, error) {
return strconv.ParseFloat(m[1], 64)
}

// parseRtime extracts the elapsed seconds from ffmpeg -benchmark: the measure
// for several threads, whose user CPU time is the sum over the threads.
func parseRtime(s string) (float64, error) {
m := rtimeRE.FindStringSubmatch(s)
if m == nil {
return 0, fmt.Errorf("no bench line with rtime 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()
Expand Down Expand Up @@ -194,17 +208,21 @@ func writePNG(fn string, m image.Image) error {
}

func speedCmd() *cobra.Command {
var w, h, ow, oh, frames, core, rounds int
var w, h, ow, oh, frames, core, rounds, threads int
var cpus string
c := &cobra.Command{
Use: "speed",
Short: "ms per frame of ffmpeg's scale filter, one thread",
Short: "ms per frame of ffmpeg's scale filter, on one thread or several",
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")
if frames < 1 || rounds < 1 || threads < 1 {
return fmt.Errorf("--frames, --rounds and --threads must be positive")
}
if cpus == "" && core >= 0 {
cpus = strconv.Itoa(core)
}
return speed(cmd, w, h, ow, oh, frames, core, rounds)
return speed(cmd, w, h, ow, oh, frames, cpus, rounds, threads)
},
}
f := c.Flags()
Expand All @@ -215,29 +233,37 @@ func speedCmd() *cobra.Command {
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")
f.IntVar(&threads, "threads", 1, "threads of the scaler: above 1, ffmpeg gets -threads 0 -filter_threads N, swscale threads=N, and elapsed time is measured")
f.StringVar(&cpus, "cpus", "", "pin to this taskset CPU list (Linux), e.g. 0-12,14-28; overrides --core")
return c
}

func speed(cmd *cobra.Command, w, h, ow, oh, frames, core, rounds int) error {
func speed(cmd *cobra.Command, w, h, ow, oh, frames int, cpus string, rounds, threads int) error {
// One thread: user CPU time, which a busy machine inflates least. Several:
// elapsed time, the CPU time being the sum over the threads.
parse, what, th, sws := parseUtime, "utime", []string{"1", "1"}, ""
if threads > 1 {
parse, what, th, sws = parseRtime, "elapsed", []string{"0", strconv.Itoa(threads)}, ":threads="+strconv.Itoa(threads)
}
run := func(vf string) (float64, error) {
a := []string{"-benchmark", "-threads", "1", "-filter_threads", "1", "-f", "lavfi", "-i",
a := []string{"-benchmark", "-threads", th[0], "-filter_threads", th[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...)
if cpus != "" {
name, argv = "taskset", append([]string{"-c", cpus, "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))
return parse(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)},
{"bilinear", fmt.Sprintf("scale=%d:%d:flags=bilinear%s,format=rgba", ow, oh, sws)},
{"bicubic", fmt.Sprintf("scale=%d:%d:flags=bicubic%s,format=rgba", ow, oh, sws)},
{"lanczos", fmt.Sprintf("scale=%d:%d:flags=lanczos%s,format=rgba", ow, oh, sws)},
}
best := map[string]float64{}
for r := 0; r < rounds; r++ {
Expand All @@ -252,7 +278,7 @@ func speed(cmd *cobra.Command, w, h, ow, oh, frames, core, rounds int) error {
}
}
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)
fmt.Fprintf(out, "ffmpeg scale %dx%d -> %dx%d, rgba out, %d thread(s), best of %d, ms/frame (%s minus source and conversion):\n", w, h, ow, oh, threads, rounds, what)
for _, c := range cfgs {
fmt.Fprintf(out, "%s\t%.2f\n", c.name, 1000*(best[c.name]-best["base"])/float64(frames))
}
Expand Down
11 changes: 11 additions & 0 deletions tools/fsrbench/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ for a; do last="$a"; done
case "$all" in
*-benchmark*)
case "$all" in
*threads=16*) echo "bench: utime=2.000s stime=0.100s rtime=0.500s";;
*filter_threads\ 16*) echo "bench: utime=1.000s stime=0.100s rtime=0.200s";;
*scale=*) echo "bench: utime=2.000s";;
*) echo "bench: utime=1.000s";;
esac;;
Expand Down Expand Up @@ -271,6 +273,14 @@ func TestSpeed(t *testing.T) {
if err != nil || !strings.Contains(out, "lanczos\t10.00") {
t.Errorf("taskset path: %v %s", err, out)
}
// Sixteen threads: elapsed time, (0.5 s - 0.2 s) / 100 frames = 3 ms.
out, err = runCmd(t, "speed", "--frames", "100", "--rounds", "1", "--threads", "16", "--cpus", "0-3")
if err != nil || !strings.Contains(out, "lanczos\t3.00") || !strings.Contains(out, "16 thread(s)") || !strings.Contains(out, "elapsed") {
t.Errorf("threads path: %v %s", err, out)
}
// An ffmpeg whose bench line has no elapsed time cannot answer for threads.
_, err = runCmd(t, "speed", "--rounds", "1", "--threads", "2")
wantErr(t, nil, err, "no bench line with rtime")
}

func TestSpeedRefusals(t *testing.T) {
Expand All @@ -281,6 +291,7 @@ func TestSpeedRefusals(t *testing.T) {
}{
{[]string{"speed", "--frames", "0"}, "must be positive"},
{[]string{"speed", "--rounds", "0"}, "must be positive"},
{[]string{"speed", "--threads", "0"}, "must be positive"},
{[]string{"speed", "x"}, "unknown command"},
} {
_, err := runCmd(t, c.args...)
Expand Down
116 changes: 116 additions & 0 deletions upscale/adversarial_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package upscale

import (
"errors"
"image"
"math"
"math/rand"
"testing"

"github.com/go-avkit/avkit/upscale/fsrref"
)

// against returns the worst difference from the oracle of EASU alone, and how
// many samples lie outside ErrorBound, of how many.
func against(p *planes, ow, oh int) (worst float64, outside, total int) {
want := fsrref.Upscale(p.to64(), ow, oh, -1)
runWorkers(p, ow, oh, -1, 1, func(y int, r, g, b, _ []float32) {
for x := 0; x < ow; x++ {
for q, v := range [3]float32{r[x], g[x], b[x]} {
d := math.Abs(float64(v) - want.Pix[y*ow+x][q])
total++
worst = max(worst, d)
if d > ErrorBound {
outside++
}
}
}
})
return
}

// TestPhaseTies: when the two sizes, reduced, are both odd, the position of
// every other output sample in the source is an integer. Computed in floats,
// a float32 and a float64 floor disagreed there and picked footprints one
// sample apart: a saturated diagonal edge at 3x was off by 0.064 (found by
// review of go-avkit/avkit#149; 640x360 to 1920x1080 is such a ratio). The
// position is an integer computation now, here and in the oracle.
func TestPhaseTies(t *testing.T) {
for _, c := range []pair{{16, 16, 48, 48}, {21, 15, 35, 25}, {16, 16, 32, 32}, {9, 7, 15, 21}} {
p := newPlanes(c.sw, c.sh, false)
for y := 0; y < c.sh; y++ {
for x := 0; x < c.sw; x++ {
v := uint8(0)
if x*3 > y*2+c.sw/4 {
v = 255
}
i := p.at(x, y)
p.r[i], p.g[i], p.b[i] = lut8[v], lut8[0], lut8[255]
}
}
p.finish()
worst, outside, total := against(p, c.ow, c.oh)
t.Logf("%v: worst %.3g, %d of %d outside %g", c, worst, outside, total, ErrorBound)
if outside != 0 {
t.Errorf("%v: %d samples outside the bound, worst %g", c, outside, worst)
}
}
}

// TestOracleLowContrast states what ErrorBound does NOT cover. On noise of at
// most 3 levels of 255 around a base, a fraction of the samples differs from
// the oracle by more than the bound: 0.9 % of 1.2 million when measured, by
// up to 4.7e-3. The cause is not established (the edge analysis divides
// differences of nearly equal lumas, which is the suspect; go-avkit/avkit#141
// carries it); what holds, and is asserted, is that EASU clamps to the four
// nearest source pixels in both computations, so no sample is off by more
// than the local range of 3 levels, and that the fraction stays under 3 %.
func TestOracleLowContrast(t *testing.T) {
rng := rand.New(rand.NewSource(1))
worst, outside, total := 0.0, 0, 0
for it := 0; it < 200; it++ {
sw, sh := 8+rng.Intn(30), 8+rng.Intn(30)
ow, oh := sw+rng.Intn(2*sw), sh+rng.Intn(2*sh)
p := newPlanes(sw, sh, false)
base := uint8(rng.Intn(250))
for y := 0; y < sh; y++ {
for x := 0; x < sw; x++ {
i := p.at(x, y)
p.r[i], p.g[i], p.b[i] = lut8[base+uint8(rng.Intn(4))], lut8[base+uint8(rng.Intn(4))], lut8[base+uint8(rng.Intn(4))]
}
}
p.finish()
w, o, n := against(p, ow, oh)
worst, outside, total = max(worst, w), outside+o, total+n
}
t.Logf("low contrast: worst %.3g, %d of %d outside %g", worst, outside, total, ErrorBound)
if local := 3.0/255 + ErrorBound; worst > local {
t.Errorf("worst error %g exceeds the local range %g", worst, local)
}
if 100*outside > 3*total {
t.Errorf("%d of %d samples outside the bound, more than 3 %%", outside, total)
}
}

// TestScalerRefusesShortDst: a destination whose buffer does not hold its
// rectangle, or whose stride is under a row, is refused before a worker
// writes outside it (a panic in a worker goroutine cannot be recovered).
func TestScalerRefusesShortDst(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 8, 8))
s := NewScaler(&Options{Sharpness: 0.2, Workers: 2})
for name, dst := range map[string]*image.RGBA{
"short buffer": {Rect: image.Rect(0, 0, 16, 16), Stride: 64, Pix: make([]byte, 512)},
"one byte short": {Rect: image.Rect(0, 0, 16, 16), Stride: 64, Pix: make([]byte, 15*64+63)},
"zero stride": {Rect: image.Rect(0, 0, 16, 16), Stride: 0, Pix: make([]byte, 1024)},
"narrow stride": {Rect: image.Rect(0, 0, 16, 16), Stride: 63, Pix: make([]byte, 1024)},
} {
if err := s.Upscale(dst, src); !errors.Is(err, ErrDst) {
t.Errorf("%s: got %v, want ErrDst", name, err)
}
}
// The exact size, with no slack after the last row, is accepted.
exact := &image.RGBA{Rect: image.Rect(3, 5, 19, 21), Stride: 64, Pix: make([]byte, 15*64+64)}
if err := s.Upscale(exact, src); err != nil {
t.Fatal(err)
}
}
23 changes: 23 additions & 0 deletions upscale/bench_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
package upscale

import (
"fmt"
"image"
"testing"
)

// BenchmarkScaler720to1080 is the video case: one Scaler, frame after frame,
// on a fixed number of workers. It reports no allocation.
func BenchmarkScaler720to1080(b *testing.B) {
for _, workers := range []int{1, 2, 4, 8, 16} {
b.Run(fmt.Sprintf("workers=%d", workers), func(b *testing.B) {
src := benchSrc(1280, 720)
dst := image.NewRGBA(image.Rect(0, 0, 1920, 1080))
s := NewScaler(&Options{Sharpness: 0.2, Workers: workers})
if err := s.Upscale(dst, src); err != nil { // the first frame allocates
b.Fatal(err)
}
b.SetBytes(1920 * 1080)
b.ReportAllocs()
for b.Loop() {
if err := s.Upscale(dst, src); err != nil {
b.Fatal(err)
}
}
})
}
}

func benchSrc(w, h int) *image.YCbCr {
m := image.NewYCbCr(image.Rect(0, 0, w, h), image.YCbCrSubsampleRatio420)
for y := 0; y < h; y++ {
Expand Down
Loading
Loading