diff --git a/README.md b/README.md index a6db433..2743197 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 ` 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 `, +`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 diff --git a/tools/fsrbench/main.go b/tools/fsrbench/main.go index 5f2ca27..c8e8e6d 100644 --- a/tools/fsrbench/main.go +++ b/tools/fsrbench/main.go @@ -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 @@ -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 ) @@ -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() @@ -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() @@ -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++ { @@ -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)) } diff --git a/tools/fsrbench/main_test.go b/tools/fsrbench/main_test.go index 3a16cfa..7e603a5 100644 --- a/tools/fsrbench/main_test.go +++ b/tools/fsrbench/main_test.go @@ -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;; @@ -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) { @@ -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...) diff --git a/upscale/adversarial_test.go b/upscale/adversarial_test.go new file mode 100644 index 0000000..8704ebc --- /dev/null +++ b/upscale/adversarial_test.go @@ -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) + } +} diff --git a/upscale/bench_test.go b/upscale/bench_test.go index 0e58cd6..14f08f9 100644 --- a/upscale/bench_test.go +++ b/upscale/bench_test.go @@ -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++ { diff --git a/upscale/easu.go b/upscale/easu.go index 4690775..f0ec028 100644 --- a/upscale/easu.go +++ b/upscale/easu.go @@ -3,7 +3,11 @@ package upscale // Port of FsrEasuF (ffx_fsr1.h, 32-bit float path), Copyright (c) 2021 // Advanced Micro Devices, Inc., MIT licence (LICENSE-FSR1.txt). -import "math" +import ( + "math" + + "github.com/go-avkit/avkit/upscale/fsrref" +) // FSR's integer-trick approximations (ffx_a.h, APrxLoRcpF1 and friends). func rcpLo(a float32) float32 { @@ -140,15 +144,11 @@ type axis struct { } func newAxis(in, out int) axis { - rcp := float32(1) / float32(out) - scale := float32(in) * rcp - off := 0.5*float32(in)*rcp - 0.5 a := axis{fp: make([]int32, out), pp: make([]float32, out)} for i := range a.fp { - pp := float32(i)*scale + off - fp := float32(math.Floor(float64(pp))) + fp, num, den := fsrref.Phase(in, out, i) a.fp[i] = int32(fp) - a.pp[i] = pp - fp + a.pp[i] = float32(num) / float32(den) } return a } diff --git a/upscale/easu_simd.go b/upscale/easu_simd.go index 0419ed3..45dba46 100644 --- a/upscale/easu_simd.go +++ b/upscale/easu_simd.go @@ -28,9 +28,21 @@ func useVec() bool { return bc(0).Len() >= 4 } func init() { if useVec() { newEasuFn, rcasRowFn, packOpaqueFn = newEasuVec, rcasRowVec, packOpaqueVec + lumaRowFn = lumaRowVec } } +// lumaRowVec is lumaRow in vectors, the ragged tail by the scalar code. +func lumaRowVec(l, r, g, b []float32) { + n, half := bc(0).Len(), bc(0.5) + x := 0 + for ; x+n <= len(l); x += n { + lr := simd.LoadFloat32s(r[x:]).Mul(half).Add(simd.LoadFloat32s(g[x:])) + simd.LoadFloat32s(b[x:]).Mul(half).Add(lr).Store(l[x:]) + } + lumaRow(l[x:], r[x:], g[x:], b[x:]) +} + func bc(v float32) simd.Float32s { return simd.BroadcastFloat32s(v) } func vRcpLo(a simd.Float32s) simd.Float32s { @@ -89,13 +101,14 @@ type bandRows [4]*bandRow // easuVec is the per-frame state of the vector EASU. type easuVec struct { p *planes + gen uint32 // the picture (planes.gen) the ring was filled from ow, owp int // output width, and it rounded up to whole vectors n int // vector length fx []int32 // integer position of the "f" tap per output column (padded) ppx []float32 // fractional position per output column (padded) ring [4]bandRow - sa [3][]float32 // analysis of the source row being filled, index x+1 - offx [12][]float32 // tapDX[k] - ppx per output column (padded) + sa [3][]float32 // analysis of the source row being filled, index x+1 + offd [4][]float32 // dx - ppx per output column (padded), for dx -1..2 gather func(s *bandRow, o int) lerp func(s *bandRow) } @@ -110,10 +123,10 @@ func newEasuState(p *planes, ax axis, ow int) *easuVec { j := min(ox, ow-1) // spare lanes repeat the last pixel e.fx[ox], e.ppx[ox] = ax.fp[j], ax.pp[j] } - for k := range e.offx { - e.offx[k] = make([]float32, e.owp) + for d := range e.offd { + e.offd[d] = make([]float32, e.owp) for ox, px := range e.ppx { - e.offx[k][ox] = tapDX[k] - px + e.offd[d][ox] = float32(d-1) - px } } buf := make([]float32, len(e.ring)*(nCh*4+3)*e.owp) @@ -188,13 +201,23 @@ func (e *easuVec) lerpScalar(s *bandRow) { } } -// tap returns tap k of channel c for the pixels starting at output x0. -func (rows *bandRows) tap(c, k, x0 int) simd.Float32s { - return simd.LoadFloat32s(rows[int(tapDY[k])+1].col[c][int(tapDX[k])+1][x0:]) -} +// tapCol and tapRow are the column (dx+1) and the row (dy+1) of each tap in +// the 4x4 footprint. +var tapCol, tapRow = func() (c, r [12]int) { + for k := range c { + c[k], r[k] = int(tapDX[k])+1, int(tapDY[k])+1 + } + return +}() // row is the easuRower of the vector kernel. func (e *easuVec) row(fy int, py float32, dr, dg, db []float32) { + if e.gen != e.p.gen { // the planes hold another picture: the ring is stale + e.gen = e.p.gen + for i := range e.ring { + e.ring[i].y = -1 << 30 + } + } var rows bandRows // source rows fy-1..fy+2 for k := range rows { y := fy - 1 + k @@ -207,8 +230,13 @@ func (e *easuVec) row(fy int, py float32, dr, dg, db []float32) { rc.one, rc.zero, rc.ppy = bc(1), bc(0), bc(py) rc.ipy = rc.one.Sub(rc.ppy) rc.c04, rc.c2516, rc.c2516m = bc(2.0/5.0), bc(25.0/16.0), bc(25.0/16.0-1.0) - for k := range rc.offy { - rc.offy[k] = bc(tapDY[k] - py) + for d := range rc.offy { + rc.offy[d] = bc(float32(d-1) - py) + } + for k := range tapCol { + for c := range rc.tap { + rc.tap[c][k] = rows[tapRow[k]].col[c][tapCol[k]] + } } for x0 := 0; x0 < e.owp; x0 += e.n { e.block(&rows, &rc, x0, dr, dg, db) @@ -220,7 +248,8 @@ func (e *easuVec) row(fy int, py float32, dr, dg, db []float32) { type rowConst struct { one, zero, ppy, ipy simd.Float32s c04, c2516, c2516m simd.Float32s - offy [12]simd.Float32s + offy [4]simd.Float32s // dy - ppy, for dy -1..2 + tap [nCh][12][]float32 // the row of each tap, per channel } // block computes the pixels x0.. of an output row (one vector's worth). @@ -248,11 +277,22 @@ func (e *easuVec) block(rows *bandRows, rc *rowConst, x0 int, dr, dg, db []float lob := bc(0.5).Add(bc((1.0/4.0 - 0.04) - 0.5).Mul(ln)) clp := vRcpLo(lob) + // The rotated, stretched offset of a tap is linear in (offx, offy), + // and the 12 taps share 4 values of each: the two halves of vx and + // of vy are made once per column and once per row of the footprint, + // and a tap adds two of them. + xx, xy, yx, yy := dirX.Mul(lx), dirY.Mul(lx), dirY.Neg().Mul(ly), dirX.Mul(ly) + var vxc, vyc, vxr, vyr [4]simd.Float32s + for d := range vxc { + o := simd.LoadFloat32s(e.offd[d][x0:]) + vxc[d], vyc[d] = o.Mul(xx), o.Mul(yx) + vxr[d], vyr[d] = rc.offy[d].Mul(xy), rc.offy[d].Mul(yy) + } + aR, aG, aB, aW := zero, zero, zero, zero - for k := range tapDX { - offx := simd.LoadFloat32s(e.offx[k][x0:]) - vx := offx.Mul(dirX).Add(rc.offy[k].Mul(dirY)).Mul(lx) - vy := offx.Mul(dirY.Neg()).Add(rc.offy[k].Mul(dirX)).Mul(ly) + for k := range tapCol { + vx := vxc[tapCol[k]].Add(vxr[tapRow[k]]) + vy := vyc[tapCol[k]].Add(vyr[tapRow[k]]) d2 := vx.Mul(vx).Add(vy.Mul(vy)).Min(clp) wB := rc.c04.Mul(d2).Sub(one) wA := lob.Mul(d2).Sub(one) @@ -260,15 +300,18 @@ func (e *easuVec) block(rows *bandRows, rc *rowConst, x0 int, dr, dg, db []float wA = wA.Mul(wA) wB = rc.c2516.Mul(wB).Sub(rc.c2516m) w := wB.Mul(wA) - aR = aR.Add(rows.tap(chR, k, x0).Mul(w)) - aG = aG.Add(rows.tap(chG, k, x0).Mul(w)) - aB = aB.Add(rows.tap(chB, k, x0).Mul(w)) + aR = aR.Add(simd.LoadFloat32s(rc.tap[chR][k][x0:]).Mul(w)) + aG = aG.Add(simd.LoadFloat32s(rc.tap[chG][k][x0:]).Mul(w)) + aB = aB.Add(simd.LoadFloat32s(rc.tap[chB][k][x0:]).Mul(w)) aW = aW.Add(w) } rcp := one.Div(aW) - vFinish(aR, rcp, rows.tap(chR, 4, x0), rows.tap(chR, 9, x0), rows.tap(chR, 3, x0), rows.tap(chR, 6, x0), dr[x0:]) - vFinish(aG, rcp, rows.tap(chG, 4, x0), rows.tap(chG, 9, x0), rows.tap(chG, 3, x0), rows.tap(chG, 6, x0), dg[x0:]) - vFinish(aB, rcp, rows.tap(chB, 4, x0), rows.tap(chB, 9, x0), rows.tap(chB, 3, x0), rows.tap(chB, 6, x0), db[x0:]) + for c, dst := range [nCh][]float32{dr, dg, db} { + t := &rc.tap[c] + a := [nCh]simd.Float32s{aR, aG, aB}[c] + // f, g, j, k are taps 4, 9, 3, 6. + vFinish(a, rcp, simd.LoadFloat32s(t[4][x0:]), simd.LoadFloat32s(t[9][x0:]), simd.LoadFloat32s(t[3][x0:]), simd.LoadFloat32s(t[6][x0:]), dst[x0:]) + } } } @@ -315,13 +358,17 @@ func vnmax(a, b simd.Float32s) simd.Float32s { } // rcasRowVec is rcasRow for the whole row: the interior in vectors, the -// first pixel and the ragged tail by the scalar code (edge clamping). +// first and the last pixel by the scalar code (edge clamping). The last +// vector is moved back to end on the last interior pixel, so that it overlaps +// the one before instead of leaving a ragged tail to the scalar code: a pixel +// computed twice gets the same value twice (out is not an input). func rcasRowVec(w int, sharp float32, u, m, d, out rowBuf) { n := bc(0).Len() x := min(1, w) rcasRow(w, 0, x, sharp, u.r, u.g, u.b, m.r, m.g, m.b, d.r, d.g, d.b, out.r, out.g, out.b) one, four, vsharp := bc(1), bc(4), bc(sharp) - for ; x+n+1 <= w; x += n { + last := w - 1 - n // where the last whole vector of interior pixels starts + for ; x <= last; x = min(x+n, max(last, x+1)) { var lobe simd.Float32s var chans [3]struct{ b, dd, e, f, h simd.Float32s } for c, p := range [3][4][]float32{{u.r, m.r, d.r, out.r}, {u.g, m.g, d.g, out.g}, {u.b, m.b, d.b, out.b}} { @@ -346,5 +393,8 @@ func rcasRowVec(w int, sharp float32, u, m, d, out rowBuf) { lobe.Mul(s.b).Add(lobe.Mul(s.dd)).Add(lobe.Mul(s.h)).Add(lobe.Mul(s.f)).Add(s.e).Mul(rcp).Store(o[x:]) } } + if last >= 1 { + x = w - 1 + } rcasRow(w, x, w, sharp, u.r, u.g, u.b, m.r, m.g, m.b, d.r, d.g, d.b, out.r, out.g, out.b) } diff --git a/upscale/easu_simd_test.go b/upscale/easu_simd_test.go index 1294f91..4e45a87 100644 --- a/upscale/easu_simd_test.go +++ b/upscale/easu_simd_test.go @@ -30,6 +30,26 @@ func TestPackOpaqueVec(t *testing.T) { } } +// TestLumaVec: the vector luma has the bits of the scalar one (halving is +// exact), for lengths on both sides of the vector length. +func TestLumaVec(t *testing.T) { + rng := rand.New(rand.NewSource(11)) + for n := 0; n <= 70; n++ { + r, g, b := make([]float32, n), make([]float32, n), make([]float32, n) + for i := range r { + r[i], g[i], b[i] = rng.Float32(), rng.Float32(), rng.Float32() + } + want, got := make([]float32, n), make([]float32, n) + lumaRow(want, r, g, b) + lumaRowVec(got, r, g, b) + for i := range want { + if math.Float32bits(got[i]) != math.Float32bits(want[i]) { + t.Fatalf("n=%d i=%d: vector %v, scalar %v", n, i, got[i], want[i]) + } + } + } +} + // TestScalarKernelsStillRun swaps the scalar kernels back in, so that the // vector lane's coverage gate also covers the fallback used on hardware // without a wide enough vector, and checks both pipelines agree to one level. diff --git a/upscale/fsrref/fsrref.go b/upscale/fsrref/fsrref.go new file mode 100644 index 0000000..cf4ec01 --- /dev/null +++ b/upscale/fsrref/fsrref.go @@ -0,0 +1,208 @@ +// Package fsrref is a float64 transliteration of FsrEasuF and FsrRcasF from +// ffx_fsr1.h (AMD FidelityFX Super Resolution 1.0, MIT licence, copyright (c) +// 2021 Advanced Micro Devices, Inc.; the notice is in ../LICENSE-FSR1.txt). +// +// It is the oracle the fast paths of the upscale package (scalar, vector, +// multicore, GPU) are held to: each must stay within upscale.ErrorBound of +// it. It is written from the C source one pixel at a time, shares no code +// with those paths, and is slow on purpose. FSR's own approximations +// (APrxLoRcpF1, APrxLoRsqF1, APrxMedRcpF1) are part of its definition and are +// applied as bit tricks to float32(x). Edges are clamped. +package fsrref + +import "math" + +// Image is a W x H picture of RGB samples on a 0..1 scale, in row order. +type Image struct { + W, H int + Pix [][3]float64 +} + +// New returns a black w x h image. +func New(w, h int) *Image { return &Image{w, h, make([][3]float64, w*h)} } + +// At returns the pixel at (x, y), with coordinates clamped to the image. +func (m *Image) At(x, y int) [3]float64 { + x = min(max(x, 0), m.W-1) + y = min(max(y, 0), m.H-1) + return m.Pix[y*m.W+x] +} + +func aprxLoRcp(a float64) float64 { + return float64(math.Float32frombits(0x7ef07ebb - math.Float32bits(float32(a)))) +} + +func aprxLoRsq(a float64) float64 { + return float64(math.Float32frombits(0x5f347d74 - math.Float32bits(float32(a))>>1)) +} + +func aprxMedRcp(a float64) float64 { + b := float64(math.Float32frombits(0x7ef19fff - math.Float32bits(float32(a)))) + return b * (-b*a + 2) +} + +func sat(a float64) float64 { return math.Min(1, math.Max(0, a)) } + +func luma(c [3]float64) float64 { return c[2]*0.5 + (c[0]*0.5 + c[1]) } + +func easuSet(dir *[2]float64, ln *float64, w float64, a, b, c, d, e float64) { + lenX := aprxLoRcp(math.Max(math.Abs(d-c), math.Abs(c-b))) + dirX := d - b + dir[0] += dirX * w + lenX = sat(math.Abs(dirX) * lenX) + lenX *= lenX + *ln += lenX * w + lenY := aprxLoRcp(math.Max(math.Abs(e-c), math.Abs(c-a))) + dirY := e - a + dir[1] += dirY * w + lenY = sat(math.Abs(dirY) * lenY) + lenY *= lenY + *ln += lenY * w +} + +// Phase is the position in a source axis of in samples of output sample i of +// out: (i+0.5)*in/out - 0.5, as its floor f and its fraction num/den, with +// 0 <= num < den. It is exact, in integers. The reference computes it in +// floats, where it lands on an integer whenever in and out, reduced, are both +// odd, and the floor is then decided by rounding: two precisions pick +// footprints one sample apart there, and differ by the local colour range. +func Phase(in, out, i int) (f int, num, den int64) { + den = 2 * int64(out) + n := (2*int64(i)+1)*int64(in) - int64(out) + q := n / den + if n%den < 0 { + q-- // floor, not truncation: the first samples lie before the source + } + return int(q), n - q*den, den +} + +// EASUPixel is FsrEasuF for the output pixel (ox, oy) of an ow x oh result. +func EASUPixel(m *Image, ow, oh, ox, oy int) [3]float64 { + X, nx, dx := Phase(m.W, ow, ox) + Y, ny, dy := Phase(m.H, oh, oy) + ppx, ppy := float64(nx)/float64(dx), float64(ny)/float64(dy) + T := func(dx, dy int) [3]float64 { return m.At(X+dx, Y+dy) } + b, c := T(0, -1), T(1, -1) + e, f, g, h := T(-1, 0), T(0, 0), T(1, 0), T(2, 0) + i, j, k, l := T(-1, 1), T(0, 1), T(1, 1), T(2, 1) + n, o := T(0, 2), T(1, 2) + bL, cL, eL, fL, gL, hL := luma(b), luma(c), luma(e), luma(f), luma(g), luma(h) + iL, jL, kL, lL, nL, oL := luma(i), luma(j), luma(k), luma(l), luma(n), luma(o) + dir := [2]float64{} + ln := 0.0 + easuSet(&dir, &ln, (1-ppx)*(1-ppy), bL, eL, fL, gL, jL) + easuSet(&dir, &ln, ppx*(1-ppy), cL, fL, gL, hL, kL) + easuSet(&dir, &ln, (1-ppx)*ppy, fL, iL, jL, kL, nL) + easuSet(&dir, &ln, ppx*ppy, gL, jL, kL, lL, oL) + dirR := dir[0]*dir[0] + dir[1]*dir[1] + zro := dirR < 1.0/32768.0 + dirR = aprxLoRsq(dirR) + if zro { + dirR = 1 + dir[0] = 1 + } + dir[0] *= dirR + dir[1] *= dirR + ln = ln * 0.5 + ln *= ln + stretch := (dir[0]*dir[0] + dir[1]*dir[1]) * aprxLoRcp(math.Max(math.Abs(dir[0]), math.Abs(dir[1]))) + len2 := [2]float64{1 + (stretch-1)*ln, 1 - 0.5*ln} + lob := 0.5 + ((1.0/4.0-0.04)-0.5)*ln + clp := aprxLoRcp(lob) + var aC [3]float64 + aW := 0.0 + tap := func(ofx, ofy float64, c [3]float64) { + ofx -= ppx + ofy -= ppy + vx := ofx*dir[0] + ofy*dir[1] + vy := ofx*-dir[1] + ofy*dir[0] + vx *= len2[0] + vy *= len2[1] + d2 := math.Min(vx*vx+vy*vy, clp) + wB := 2.0/5.0*d2 - 1 + wA := lob*d2 - 1 + wB *= wB + wA *= wA + wB = 25.0/16.0*wB - (25.0/16.0 - 1.0) + w := wB * wA + for q := 0; q < 3; q++ { + aC[q] += c[q] * w + } + aW += w + } + tap(0, -1, b) + tap(1, -1, c) + tap(-1, 1, i) + tap(0, 1, j) + tap(0, 0, f) + tap(-1, 0, e) + tap(1, 1, k) + tap(2, 1, l) + tap(2, 0, h) + tap(1, 0, g) + tap(1, 2, o) + tap(0, 2, n) + var out [3]float64 + for q := 0; q < 3; q++ { + mn := math.Min(math.Min(f[q], g[q]), math.Min(j[q], k[q])) + mx := math.Max(math.Max(f[q], g[q]), math.Max(j[q], k[q])) + out[q] = math.Min(mx, math.Max(mn, aC[q]/aW)) + } + return out +} + +// gpuMax is max() as GPUs evaluate it: a NaN operand yields the other one. +func gpuMax(a, b float64) float64 { + if math.IsNaN(a) { + return b + } + if math.IsNaN(b) { + return a + } + return math.Max(a, b) +} + +// RCASPixel is FsrRcasF (no denoise) for the pixel (x, y) of m; sharp is the +// linear constant of FsrRcasCon, exp2(-stops). +func RCASPixel(m *Image, x, y int, sharp float64) [3]float64 { + b, d, e, f, h := m.At(x, y-1), m.At(x-1, y), m.At(x, y), m.At(x+1, y), m.At(x, y+1) + var mn4, mx4, lobeC [3]float64 + lobe := math.Inf(-1) + for q := 0; q < 3; q++ { + mn4[q] = math.Min(math.Min(math.Min(b[q], d[q]), f[q]), h[q]) + mx4[q] = math.Max(math.Max(math.Max(b[q], d[q]), f[q]), h[q]) + hitMin := math.Min(mn4[q], e[q]) * (1 / (4 * mx4[q])) + hitMax := (1 - math.Max(mx4[q], e[q])) * (1 / (4*mn4[q] - 4)) + lobeC[q] = gpuMax(-hitMin, hitMax) + lobe = gpuMax(lobe, lobeC[q]) + } + lobe = gpuMax(-(0.25-1.0/16.0), math.Min(lobe, 0)) * sharp + rcp := aprxMedRcp(4*lobe + 1) + var out [3]float64 + for q := 0; q < 3; q++ { + out[q] = (lobe*b[q] + lobe*d[q] + lobe*h[q] + lobe*f[q] + e[q]) * rcp + } + return out +} + +// Upscale scales m to ow x oh with EASU and, when stops >= 0, sharpens the +// result with RCAS at that many stops of attenuation (0 is the sharpest). +func Upscale(m *Image, ow, oh int, stops float64) *Image { + e := New(ow, oh) + for y := 0; y < oh; y++ { + for x := 0; x < ow; x++ { + e.Pix[y*ow+x] = EASUPixel(m, ow, oh, x, y) + } + } + if !(stops >= 0) { + return e + } + sharp := math.Exp2(-stops) + r := New(ow, oh) + for y := 0; y < oh; y++ { + for x := 0; x < ow; x++ { + r.Pix[y*ow+x] = RCASPixel(e, x, y, sharp) + } + } + return r +} diff --git a/upscale/fsrref/fsrref_test.go b/upscale/fsrref/fsrref_test.go new file mode 100644 index 0000000..d95f4be --- /dev/null +++ b/upscale/fsrref/fsrref_test.go @@ -0,0 +1,60 @@ +package fsrref + +import ( + "math" + "testing" +) + +// A flat picture stays flat through EASU and RCAS: every tap has the same +// colour, so the normalised sum is that colour whatever the weights. +func TestFlatStaysFlat(t *testing.T) { + m := New(7, 5) + for i := range m.Pix { + m.Pix[i] = [3]float64{0.25, 0.5, 0.75} + } + for _, stops := range []float64{-1, 0, 2} { + out := Upscale(m, 13, 9, stops) + if out.W != 13 || out.H != 9 { + t.Fatalf("size %dx%d", out.W, out.H) + } + for i, px := range out.Pix { + for q, v := range px { + // RCAS normalises with FSR's approximate reciprocal, which is + // 0.32 % low at the 1/4 a flat picture gives it. + if math.Abs(v-m.Pix[0][q]) > 4e-3*m.Pix[0][q] { + t.Fatalf("stops=%v px %d ch %d: %v", stops, i, q, v) + } + } + } + } +} + +// At clamps its coordinates to the picture. +func TestAtClamps(t *testing.T) { + m := New(2, 2) + m.Pix = [][3]float64{{1}, {2}, {3}, {4}} + for _, c := range []struct { + x, y int + want float64 + }{{-5, -5, 1}, {9, -1, 2}, {-1, 9, 3}, {9, 9, 4}, {1, 0, 2}} { + if got := m.At(c.x, c.y)[0]; got != c.want { + t.Errorf("At(%d,%d) = %v, want %v", c.x, c.y, got, c.want) + } + } +} + +// On a black ring RCAS divides by zero in the reference; the GPU max keeps +// the result finite, and a NaN operand on either side yields the other. +func TestBlackRingFinite(t *testing.T) { + m := New(3, 3) + m.Pix[4] = [3]float64{0.8, 0.1, 0.3} + for _, v := range RCASPixel(m, 1, 1, 1) { + if math.IsNaN(v) || math.IsInf(v, 0) { + t.Fatalf("not finite: %v", v) + } + } + nan := math.NaN() + if gpuMax(nan, 2) != 2 || gpuMax(3, nan) != 3 || gpuMax(1, 4) != 4 { + t.Fatal("gpuMax") + } +} diff --git a/upscale/fsrref/phase_test.go b/upscale/fsrref/phase_test.go new file mode 100644 index 0000000..8f4fdef --- /dev/null +++ b/upscale/fsrref/phase_test.go @@ -0,0 +1,37 @@ +package fsrref + +import ( + "math/big" + "testing" +) + +// TestPhase checks the integer position against exact rationals: f + num/den +// is (i+0.5)*in/out - 0.5, with 0 <= num < den, for every sample of ratios +// that include the ones whose positions are integers (both sizes odd). +func TestPhase(t *testing.T) { + for _, c := range [][2]int{{1, 1}, {1, 4}, {16, 48}, {640, 1920}, {21, 35}, {720, 1080}, {7, 9}, {32768, 32768}} { + in, out := c[0], c[1] + ties := 0 + for i := 0; i < out; i++ { + f, num, den := Phase(in, out, i) + if num < 0 || num >= den { + t.Fatalf("%d->%d i=%d: fraction %d/%d outside [0,1)", in, out, i, num, den) + } + want := new(big.Rat).SetFrac64((2*int64(i)+1)*int64(in)-int64(out), 2*int64(out)) + got := new(big.Rat).Add(new(big.Rat).SetInt64(int64(f)), new(big.Rat).SetFrac64(num, den)) + if got.Cmp(want) != 0 { + t.Fatalf("%d->%d i=%d: got %v, want %v", in, out, i, got, want) + } + if num == 0 { + ties++ + } + } + if f, _, _ := Phase(in, out, 0); in < out && f != -1 { + t.Errorf("%d->%d: first sample has floor %d, want -1", in, out, f) + } + t.Logf("%d->%d: %d of %d positions are integers", in, out, ties, out) + } + if _, num, _ := Phase(16, 48, 1); num != 0 { + t.Errorf("16->48 sample 1 is at 0 exactly, got fraction numerator %d", num) + } +} diff --git a/upscale/oracle_test.go b/upscale/oracle_test.go index 65eebbd..3cb4667 100644 --- a/upscale/oracle_test.go +++ b/upscale/oracle_test.go @@ -4,181 +4,12 @@ import ( "math" "math/rand" "testing" -) - -// The oracle is an independent float64 transliteration of FsrEasuF and -// FsrRcasF from ffx_fsr1.h (written from the C source, sharing no code with -// the float32 implementation). FSR's own approximations (APrxLo*) are part -// of its definition and are applied as bit tricks to float32(x). - -type img64 struct { - w, h int - px [][3]float64 -} - -func (m *img64) get(x, y int) [3]float64 { - x = min(max(x, 0), m.w-1) - y = min(max(y, 0), m.h-1) - return m.px[y*m.w+x] -} - -func aprxLoRcp(a float64) float64 { - return float64(math.Float32frombits(0x7ef07ebb - math.Float32bits(float32(a)))) -} -func aprxLoRsq(a float64) float64 { - return float64(math.Float32frombits(0x5f347d74 - math.Float32bits(float32(a))>>1)) -} -func aprxMedRcp(a float64) float64 { - b := float64(math.Float32frombits(0x7ef19fff - math.Float32bits(float32(a)))) - return b * (-b*a + 2) -} -func sat64(a float64) float64 { return math.Min(1, math.Max(0, a)) } -func luma64(c [3]float64) float64 { return c[2]*0.5 + (c[0]*0.5 + c[1]) } - -func easuSet64(dir *[2]float64, ln *float64, w float64, a, b, c, d, e float64) { - lenX := aprxLoRcp(math.Max(math.Abs(d-c), math.Abs(c-b))) - dirX := d - b - dir[0] += dirX * w - lenX = sat64(math.Abs(dirX) * lenX) - lenX *= lenX - *ln += lenX * w - lenY := aprxLoRcp(math.Max(math.Abs(e-c), math.Abs(c-a))) - dirY := e - a - dir[1] += dirY * w - lenY = sat64(math.Abs(dirY) * lenY) - lenY *= lenY - *ln += lenY * w -} - -func easu64(m *img64, ow, oh, ox, oy int) [3]float64 { - cx := float64(m.w) / float64(ow) - cy := float64(m.h) / float64(oh) - ppx := float64(ox)*cx + (0.5*cx - 0.5) - ppy := float64(oy)*cy + (0.5*cy - 0.5) - fx, fy := math.Floor(ppx), math.Floor(ppy) - ppx -= fx - ppy -= fy - X, Y := int(fx), int(fy) - T := func(dx, dy int) [3]float64 { return m.get(X+dx, Y+dy) } - b, c := T(0, -1), T(1, -1) - e, f, g, h := T(-1, 0), T(0, 0), T(1, 0), T(2, 0) - i, j, k, l := T(-1, 1), T(0, 1), T(1, 1), T(2, 1) - n, o := T(0, 2), T(1, 2) - bL, cL, eL, fL, gL, hL := luma64(b), luma64(c), luma64(e), luma64(f), luma64(g), luma64(h) - iL, jL, kL, lL, nL, oL := luma64(i), luma64(j), luma64(k), luma64(l), luma64(n), luma64(o) - dir := [2]float64{} - ln := 0.0 - easuSet64(&dir, &ln, (1-ppx)*(1-ppy), bL, eL, fL, gL, jL) - easuSet64(&dir, &ln, ppx*(1-ppy), cL, fL, gL, hL, kL) - easuSet64(&dir, &ln, (1-ppx)*ppy, fL, iL, jL, kL, nL) - easuSet64(&dir, &ln, ppx*ppy, gL, jL, kL, lL, oL) - dirR := dir[0]*dir[0] + dir[1]*dir[1] - zro := dirR < 1.0/32768.0 - dirR = aprxLoRsq(dirR) - if zro { - dirR = 1 - dir[0] = 1 - } - dir[0] *= dirR - dir[1] *= dirR - ln = ln * 0.5 - ln *= ln - stretch := (dir[0]*dir[0] + dir[1]*dir[1]) * aprxLoRcp(math.Max(math.Abs(dir[0]), math.Abs(dir[1]))) - len2 := [2]float64{1 + (stretch-1)*ln, 1 - 0.5*ln} - lob := 0.5 + ((1.0/4.0-0.04)-0.5)*ln - clp := aprxLoRcp(lob) - var aC [3]float64 - aW := 0.0 - tap := func(ofx, ofy float64, c [3]float64) { - ofx -= ppx - ofy -= ppy - vx := ofx*dir[0] + ofy*dir[1] - vy := ofx*-dir[1] + ofy*dir[0] - vx *= len2[0] - vy *= len2[1] - d2 := math.Min(vx*vx+vy*vy, clp) - wB := 2.0/5.0*d2 - 1 - wA := lob*d2 - 1 - wB *= wB - wA *= wA - wB = 25.0/16.0*wB - (25.0/16.0 - 1.0) - w := wB * wA - for q := 0; q < 3; q++ { - aC[q] += c[q] * w - } - aW += w - } - tap(0, -1, b) - tap(1, -1, c) - tap(-1, 1, i) - tap(0, 1, j) - tap(0, 0, f) - tap(-1, 0, e) - tap(1, 1, k) - tap(2, 1, l) - tap(2, 0, h) - tap(1, 0, g) - tap(1, 2, o) - tap(0, 2, n) - var out [3]float64 - for q := 0; q < 3; q++ { - mn := math.Min(math.Min(f[q], g[q]), math.Min(j[q], k[q])) - mx := math.Max(math.Max(f[q], g[q]), math.Max(j[q], k[q])) - out[q] = math.Min(mx, math.Max(mn, aC[q]/aW)) - } - return out -} - -func gpuMax(a, b float64) float64 { - if math.IsNaN(a) { - return b - } - if math.IsNaN(b) { - return a - } - return math.Max(a, b) -} + "github.com/go-avkit/avkit/upscale/fsrref" +) -func rcas64(m *img64, x, y int, sharp float64) [3]float64 { - b, d, e, f, h := m.get(x, y-1), m.get(x-1, y), m.get(x, y), m.get(x+1, y), m.get(x, y+1) - var mn4, mx4, lobeC [3]float64 - lobe := math.Inf(-1) - for q := 0; q < 3; q++ { - mn4[q] = math.Min(math.Min(math.Min(b[q], d[q]), f[q]), h[q]) - mx4[q] = math.Max(math.Max(math.Max(b[q], d[q]), f[q]), h[q]) - hitMin := math.Min(mn4[q], e[q]) * (1 / (4 * mx4[q])) - hitMax := (1 - math.Max(mx4[q], e[q])) * (1 / (4*mn4[q] - 4)) - lobeC[q] = gpuMax(-hitMin, hitMax) - lobe = gpuMax(lobe, lobeC[q]) - } - lobe = gpuMax(-(0.25-1.0/16.0), math.Min(lobe, 0)) * sharp - rcp := aprxMedRcp(4*lobe + 1) - var out [3]float64 - for q := 0; q < 3; q++ { - out[q] = (lobe*b[q] + lobe*d[q] + lobe*h[q] + lobe*f[q] + e[q]) * rcp - } - return out -} - -func oracle(m *img64, ow, oh int, sharp float64, doRcas bool) *img64 { - e := &img64{ow, oh, make([][3]float64, ow*oh)} - for y := 0; y < oh; y++ { - for x := 0; x < ow; x++ { - e.px[y*ow+x] = easu64(m, ow, oh, x, y) - } - } - if !doRcas { - return e - } - r := &img64{ow, oh, make([][3]float64, ow*oh)} - for y := 0; y < oh; y++ { - for x := 0; x < ow; x++ { - r.px[y*ow+x] = rcas64(e, x, y, sharp) - } - } - return r -} +// The oracle is fsrref: an independent float64 transliteration of FsrEasuF +// and FsrRcasF from ffx_fsr1.h, sharing no code with the float32 paths. // testImage builds a deterministic 8-bit-valued image of the given kind. func testImage(kind string, w, h int, seed int64) *planes { @@ -217,12 +48,12 @@ func testImage(kind string, w, h int, seed int64) *planes { return p } -func (p *planes) to64() *img64 { - m := &img64{p.w, p.h, make([][3]float64, p.w*p.h)} +func (p *planes) to64() *fsrref.Image { + m := fsrref.New(p.w, p.h) for y := 0; y < p.h; y++ { for x := 0; x < p.w; x++ { i := p.at(x, y) - m.px[y*p.w+x] = [3]float64{float64(p.r[i]), float64(p.g[i]), float64(p.b[i])} + m.Pix[y*p.w+x] = [3]float64{float64(p.r[i]), float64(p.g[i]), float64(p.b[i])} } } return m @@ -230,41 +61,50 @@ func (p *planes) to64() *img64 { type pair struct{ sw, sh, ow, oh int } +var ( + oracleKinds = []string{"noise", "edges", "gradient", "black", "white"} + oracleSizes = []pair{{33, 21, 33, 21}, {40, 30, 60, 45}, {37, 29, 74, 58}, {24, 24, 41, 47}, {50, 20, 65, 22}} + oracleStops = []float64{-1, 0, 0.2, 1.5} +) + +// TestOracle holds the float32 pipeline to ErrorBound against fsrref, for +// one worker and for several (the bands must not change a single value). func TestOracle(t *testing.T) { - sizes := []pair{{33, 21, 33, 21}, {40, 30, 60, 45}, {37, 29, 74, 58}, {24, 24, 41, 47}, {50, 20, 65, 22}} - worst := 0.0 - var flips int - total := 0 - for _, kind := range []string{"noise", "edges", "gradient", "black", "white"} { - for _, sz := range sizes { - for _, sharp := range []float64{-1, 0, 0.2, 1.5} { - p := testImage(kind, sz.sw, sz.sh, 7) - want := oracle(p.to64(), sz.ow, sz.oh, math.Exp2(-sharp), sharp >= 0) - got := &img64{sz.ow, sz.oh, make([][3]float64, sz.ow*sz.oh)} - run(p, sz.ow, sz.oh, float32(sharp), func(y int, r, g, b, _ []float32) { - for x := 0; x < sz.ow; x++ { - got.px[y*sz.ow+x] = [3]float64{float64(r[x]), float64(g[x]), float64(b[x])} - } - }) - for i := range want.px { - for q := 0; q < 3; q++ { - d := math.Abs(got.px[i][q] - want.px[i][q]) - total++ - if d > ErrorBound { - flips++ - if flips <= 5 { - t.Logf("%s %v sharp=%v px %d ch %d: got %v want %v", kind, sz, sharp, i, q, got.px[i][q], want.px[i][q]) + for _, workers := range []int{1, 3} { + worst := 0.0 + var flips int + total := 0 + for _, kind := range oracleKinds { + for _, sz := range oracleSizes { + for _, sharp := range oracleStops { + p := testImage(kind, sz.sw, sz.sh, 7) + want := fsrref.Upscale(p.to64(), sz.ow, sz.oh, sharp) + got := fsrref.New(sz.ow, sz.oh) + runWorkers(p, sz.ow, sz.oh, float32(sharp), workers, func(y int, r, g, b, _ []float32) { + for x := 0; x < sz.ow; x++ { + got.Pix[y*sz.ow+x] = [3]float64{float64(r[x]), float64(g[x]), float64(b[x])} + } + }) + for i := range want.Pix { + for q := 0; q < 3; q++ { + d := math.Abs(got.Pix[i][q] - want.Pix[i][q]) + total++ + if d > ErrorBound { + flips++ + if flips <= 5 { + t.Logf("%s %v sharp=%v px %d ch %d: got %v want %v", kind, sz, sharp, i, q, got.Pix[i][q], want.Pix[i][q]) + } + } else if d > worst { + worst = d } - } else if d > worst { - worst = d } } } } } - } - t.Logf("max in-bound error %.3g over %d samples; %d outside %g", worst, total, flips, ErrorBound) - if flips != 0 { - t.Fatalf("%d samples exceed the stated error bound %g", flips, ErrorBound) + t.Logf("workers=%d: max in-bound error %.3g over %d samples; %d outside %g", workers, worst, total, flips, ErrorBound) + if flips != 0 { + t.Fatalf("workers=%d: %d samples exceed the stated error bound %g", workers, flips, ErrorBound) + } } } diff --git a/upscale/rcas.go b/upscale/rcas.go index d7a8642..96af292 100644 --- a/upscale/rcas.go +++ b/upscale/rcas.go @@ -4,7 +4,11 @@ package upscale // pass-through), Copyright (c) 2021 Advanced Micro Devices, Inc., MIT // licence (LICENSE-FSR1.txt). -import "math" +import ( + "image" + "math" + "sync" +) // rcasLimit is FSR_RCAS_LIMIT. const rcasLimit = 0.25 - 1.0/16.0 @@ -90,53 +94,118 @@ func newRow(w int) rowBuf { return rowBuf{s[:w:w], s[w : 2*w : 2*w], s[2*w:]} } -// run executes EASU then (when sharp >= 0) RCAS, streaming one output row -// at a time to emit. a is nil for opaque sources. -func run(p *planes, ow, oh int, sharp float32, emit func(y int, r, g, b, a []float32)) { - ax, ay := newAxis(p.w, ow), newAxis(p.h, oh) - var alpha []float32 - if p.a != nil { - alpha = make([]float32, ow) - } - easu := newEasuFn(p, ax, ow) - easuRow := func(oy int, dst rowBuf) { - easu(int(ay.fp[oy]), ay.pp[oy], dst.r, dst.g, dst.b) - } - // Bilinear alpha at the same sample position as the colour. - alphaFor := func(oy int) []float32 { - if alpha == nil { - return nil - } - fy, py := int(ay.fp[oy]), ay.pp[oy] - r0, r1 := p.at(0, fy), p.at(0, fy+1) - for ox := 0; ox < ow; ox++ { - fx, px := int(ax.fp[ox]), ax.pp[ox] - top := p.a[r0+fx]*(1-px) + p.a[r0+fx+1]*px - bot := p.a[r1+fx]*(1-px) + p.a[r1+fx+1]*px - alpha[ox] = top*(1-py) + bot*py +// emitFn receives one finished output row; a is nil for opaque sources. The +// slices are the worker's and are overwritten by its next row. Bands run +// concurrently, so it is called from several goroutines, each with its own +// rows y. +type emitFn func(y int, r, g, b, a []float32) + +// worker is what one goroutine needs to compute a band of output rows. +type worker struct { + easu easuRower + ring [3]rowBuf // EASU rows oy-1..oy+1 + out rowBuf // the sharpened row + alpha []float32 // nil for opaque sources +} + +// frame is everything a geometry needs: the source planes, the phase tables +// of both axes and the workers' buffers. It is reused from picture to +// picture as long as the geometry holds. +type frame struct { + p *planes + ow, oh int + ax, ay axis + wk []*worker +} + +func newFrame(p *planes, ow, oh, workers int) *frame { + f := &frame{p: p, ow: ow, oh: oh, ax: newAxis(p.w, ow), ay: newAxis(p.h, oh), wk: make([]*worker, workers)} + for i := range f.wk { + w := &worker{easu: newEasuFn(p, f.ax, ow), ring: [3]rowBuf{newRow(ow), newRow(ow), newRow(ow)}, out: newRow(ow)} + if p.a != nil { + w.alpha = make([]float32, ow) } - return alpha + f.wk[i] = w + } + return f +} + +func (f *frame) easuRow(w *worker, oy int, dst rowBuf) { + w.easu(int(f.ay.fp[oy]), f.ay.pp[oy], dst.r, dst.g, dst.b) +} + +// alphaRow is the bilinear alpha of output row oy, at the same sample +// position as the colour: nil, after no work, for an opaque source. +func (f *frame) alphaRow(w *worker, oy int) []float32 { + p := f.p + fy, py := int(f.ay.fp[oy]), f.ay.pp[oy] + r0, r1 := p.at(0, fy), p.at(0, fy+1) + for ox := range w.alpha { + fx, px := int(f.ax.fp[ox]), f.ax.pp[ox] + top := p.a[r0+fx]*(1-px) + p.a[r0+fx+1]*px + bot := p.a[r1+fx]*(1-px) + p.a[r1+fx+1]*px + w.alpha[ox] = top*(1-py) + bot*py } + return w.alpha +} + +// band executes EASU then (when sharp >= 0) RCAS for the output rows +// y0..y1-1, streaming one row at a time to emit. +// +// RCAS reads the EASU rows above and below, clamped to the FRAME and not to +// the band: a band computes the EASU row before its first and after its last +// itself. An EASU row is a function of the source and of its own index only, +// so the neighbouring band computes the very same values and the result does +// not depend on where the bands are cut. +func (f *frame) band(w *worker, y0, y1 int, sharp float32, emit emitFn) { if sharp < 0 { - row := newRow(ow) - for oy := 0; oy < oh; oy++ { - easuRow(oy, row) - emit(oy, row.r, row.g, row.b, alphaFor(oy)) + for oy := y0; oy < y1; oy++ { + f.easuRow(w, oy, w.out) + emit(oy, w.out.r, w.out.g, w.out.b, f.alphaRow(w, oy)) } return } k := rcasScale(sharp) - // Ring of three EASU rows, plus the sharpened output row. - ring := [3]rowBuf{newRow(ow), newRow(ow), newRow(ow)} - out := newRow(ow) - computed := -1 - for oy := 0; oy < oh; oy++ { - for computed < min(oy+1, oh-1) { + computed := max(y0-1, 0) - 1 + for oy := y0; oy < y1; oy++ { + for computed < min(oy+1, f.oh-1) { computed++ - easuRow(computed, ring[computed%3]) + f.easuRow(w, computed, w.ring[computed%3]) } - u, m, d := ring[max(oy-1, 0)%3], ring[oy%3], ring[min(oy+1, oh-1)%3] - rcasRowFn(ow, k, u, m, d, out) - emit(oy, out.r, out.g, out.b, alphaFor(oy)) + u, m, d := w.ring[max(oy-1, 0)%3], w.ring[oy%3], w.ring[min(oy+1, f.oh-1)%3] + rcasRowFn(f.ow, k, u, m, d, w.out) + emit(oy, w.out.r, w.out.g, w.out.b, f.alphaRow(w, oy)) + } +} + +// runWorkers computes the whole picture of finished planes on the given +// number of goroutines (at least one, at most one per output row). +func runWorkers(p *planes, ow, oh int, sharp float32, workers int, emit emitFn) { + n := workerCount(workers, oh) + f := newFrame(p, ow, oh, n) + var wg sync.WaitGroup + for i := 1; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + f.band(f.wk[i], oh*i/n, oh*(i+1)/n, sharp, emit) + }() } + f.band(f.wk[0], 0, oh/n, sharp, emit) + wg.Wait() +} + +// run is runWorkers on the calling goroutine alone. +func run(p *planes, ow, oh int, sharp float32, emit emitFn) { + runWorkers(p, ow, oh, sharp, 1, emit) +} + +// fromImage converts a whole image to finished planes. +func fromImage(src image.Image) *planes { + b := src.Bounds() + alpha, _ := srcKind(src) + p := newPlanes(b.Dx(), b.Dy(), alpha) + p.convert(src, 0, p.h) + p.padRows() + return p } diff --git a/upscale/scaler_test.go b/upscale/scaler_test.go new file mode 100644 index 0000000..96f8109 --- /dev/null +++ b/upscale/scaler_test.go @@ -0,0 +1,189 @@ +package upscale + +import ( + "bytes" + "errors" + "image" + "image/color" + "math" + "math/rand" + "testing" +) + +// anyImage hides the concrete type of an image, so that it takes the generic +// path; with opaque set it also answers Opaque. +type anyImage struct{ image.Image } + +type anyOpaque struct{ anyImage } + +func (anyOpaque) Opaque() bool { return true } + +// scalerSources is one picture of every kind the conversion distinguishes. +func scalerSources(seed int64) map[string]image.Image { + rng := rand.New(rand.NewSource(seed)) + const w, h = 37, 23 + fill := func(pix []uint8) { + for i := range pix { + pix[i] = uint8(rng.Intn(256)) + } + } + ycc := image.NewYCbCr(image.Rect(0, 0, w, h), image.YCbCrSubsampleRatio420) + fill(ycc.Y) + fill(ycc.Cb) + fill(ycc.Cr) + gray := image.NewGray(image.Rect(0, 0, w, h)) + fill(gray.Pix) + nrgba := image.NewNRGBA(image.Rect(0, 0, w, h)) + fill(nrgba.Pix) + opaque := image.NewNRGBA(image.Rect(0, 0, w, h)) + fill(opaque.Pix) + for i := 3; i < len(opaque.Pix); i += 4 { + opaque.Pix[i] = 255 + } + rgba := image.NewRGBA(image.Rect(0, 0, w, h)) // premultiplied, with alpha 0, partial and 255 + for i := 0; i < len(rgba.Pix); i += 4 { + a := []uint8{0, 255, uint8(rng.Intn(256))}[rng.Intn(3)] + rgba.Pix[i+3] = a + for c := 0; c < 3; c++ { + rgba.Pix[i+c] = uint8(rng.Intn(int(a) + 1)) + } + } + return map[string]image.Image{ + "ycbcr": ycc, "gray": gray, "nrgba": nrgba, "nrgba-opaque": opaque, "rgba": rgba, + "generic": anyImage{nrgba}, "generic-opaque": anyOpaque{anyImage{opaque}}, + } +} + +// TestWorkersSameBytes asserts the contract of Options.Workers: the picture +// is the same, byte for byte, for any number of bands, with and without RCAS. +func TestWorkersSameBytes(t *testing.T) { + for name, src := range scalerSources(3) { + for _, sharp := range []float32{-1, 0, 0.2} { + want, err := Upscale(src, 61, 40, &Options{Sharpness: sharp, Workers: 1}) + if err != nil { + t.Fatal(err) + } + for _, workers := range []int{0, -3, 2, 3, 7, 16, 40, 41, 100000} { + got, err := Upscale(src, 61, 40, &Options{Sharpness: sharp, Workers: workers}) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Pix, want.Pix) { + t.Fatalf("%s sharp=%v: %d workers give another picture than one", name, sharp, workers) + } + } + } + } +} + +// TestScalerReuse runs pictures of changing content, kind and size through +// one Scaler and compares each with a fresh Upscale: nothing of a previous +// picture (cached rows, alpha, un-premultiplied colour) may leak into the next. +func TestScalerReuse(t *testing.T) { + for _, workers := range []int{1, 4} { + opt := &Options{Sharpness: 0.2, Workers: workers} + s := NewScaler(opt) + a, b := scalerSources(1), scalerSources(2) + steps := []struct { + src image.Image + w, h int + }{ + {a["ycbcr"], 55, 35}, {b["ycbcr"], 55, 35}, // same geometry, new content + {a["rgba"], 55, 35}, {b["rgba"], 55, 35}, // alpha appears; transparent pixels move + {b["nrgba-opaque"], 55, 35}, // alpha goes + {a["gray"], 74, 46}, // output size changes + {a["generic"], 74, 46}, {b["generic-opaque"], 74, 46}, + } + for i, st := range steps { + want, err := Upscale(st.src, st.w, st.h, opt) + if err != nil { + t.Fatal(err) + } + got := image.NewRGBA(image.Rect(0, 0, st.w, st.h)) + if err := s.Upscale(got, st.src); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Pix, want.Pix) { + t.Fatalf("workers=%d step %d: a reused Scaler gives another picture than a fresh one", workers, i) + } + } + } +} + +// TestScalerSubImageDst writes into a window of a larger picture and checks +// that nothing outside the window is touched. +func TestScalerSubImageDst(t *testing.T) { + src := scalerSources(5)["ycbcr"] + want, err := Upscale(src, 50, 30, nil) + if err != nil { + t.Fatal(err) + } + big := image.NewRGBA(image.Rect(0, 0, 70, 50)) + for i := range big.Pix { + big.Pix[i] = 0x5a + } + win := big.SubImage(image.Rect(11, 7, 61, 37)).(*image.RGBA) + if err := NewScaler(nil).Upscale(win, src); err != nil { + t.Fatal(err) + } + for y := 0; y < 50; y++ { + for x := 0; x < 70; x++ { + got := big.RGBAAt(x, y) + exp := color.RGBA{0x5a, 0x5a, 0x5a, 0x5a} + if image.Pt(x, y).In(win.Rect) { + exp = want.RGBAAt(x-11, y-7) + } + if got != exp { + t.Fatalf("(%d,%d): got %v, want %v", x, y, got, exp) + } + } + } +} + +// TestScalerRefusals: every refusal of Upscale is one of Scaler.Upscale too. +func TestScalerRefusals(t *testing.T) { + src := image.NewGray(image.Rect(0, 0, 8, 8)) + dst := image.NewRGBA(image.Rect(0, 0, 12, 12)) + if err := NewScaler(nil).Upscale(nil, src); !errors.Is(err, ErrNilImage) { + t.Errorf("nil dst: %v", err) + } + if err := NewScaler(nil).Upscale(dst, nil); !errors.Is(err, ErrNilImage) { + t.Errorf("nil src: %v", err) + } + if err := NewScaler(nil).Upscale(image.NewRGBA(image.Rect(0, 0, 4, 4)), src); !errors.Is(err, ErrSize) { + t.Errorf("downscale: %v", err) + } + if err := NewScaler(&Options{Sharpness: float32(math.NaN())}).Upscale(dst, src); !errors.Is(err, ErrSharp) { + t.Errorf("NaN sharpness: %v", err) + } +} + +// TestSrcKind: an image that says it is opaque gets no alpha plane, one that +// says nothing gets one, and only the standard types are read concurrently. +func TestSrcKind(t *testing.T) { + s := scalerSources(4) + for name, want := range map[string][2]bool{ + "ycbcr": {false, true}, "gray": {false, true}, "nrgba": {true, true}, "nrgba-opaque": {false, true}, + "rgba": {true, true}, "generic": {true, false}, "generic-opaque": {false, false}, + } { + if alpha, conc := srcKind(s[name]); alpha != want[0] || conc != want[1] { + t.Errorf("%s: alpha %v concurrent %v, want %v", name, alpha, conc, want) + } + } +} + +// TestScalerAllocatesNothing: after the first frame of a geometry, a frame +// costs no allocation, on one worker and on several. +func TestScalerAllocatesNothing(t *testing.T) { + src := scalerSources(9)["ycbcr"] + dst := image.NewRGBA(image.Rect(0, 0, 64, 40)) + for _, workers := range []int{1, 4} { + s := NewScaler(&Options{Sharpness: 0.2, Workers: workers}) + if err := s.Upscale(dst, src); err != nil { + t.Fatal(err) + } + if n := testing.AllocsPerRun(20, func() { _ = s.Upscale(dst, src) }); n != 0 { + t.Errorf("workers=%d: %v allocations per frame, want 0", workers, n) + } + } +} diff --git a/upscale/upscale.go b/upscale/upscale.go index d28831c..b935377 100644 --- a/upscale/upscale.go +++ b/upscale/upscale.go @@ -12,13 +12,25 @@ // (c) 2021 Advanced Micro Devices, Inc.; the notice is in LICENSE-FSR1.txt). // // Accuracy contract: against a float64 transliteration of the reference -// (the oracle in the tests, which applies the same bit-level approximations) +// (package fsrref, which applies the same bit-level approximations) // the float32 pipeline stays within ErrorBound of the exact result, on a -// 0..1 colour scale, except for the measure-zero set of pixels where a -// comparison in the reference (a clamp, a min/max, the "direction is zero" -// test) flips under rounding; those are bounded by the local colour range. +// 0..1 colour scale, on the corpus of TestOracle. It 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 (TestOracleLowContrast), which EASU's clamp to the four +// nearest pixels keeps under the local colour range. The cause is not +// established; a comparison of the reference flipping under rounding (a +// clamp, a min/max, the "direction is zero" test) is one known mechanism. +// The position of an output pixel in the source is computed in integers, by +// this package and by fsrref alike: in floats it falls on an integer whenever +// the two sizes, reduced, are both odd (640 to 1920), and a float32 and a +// float64 floor then pick different footprints. // FSR operates on gamma-encoded RGB; no colour-space conversion is done // other than the JFIF YCbCr to RGB conversion of the Go standard library. +// +// A frame is shared between Options.Workers goroutines as bands of rows. +// Every output row is a function of the source alone, so the result is the +// same for any number of workers, byte for byte. For video, a Scaler keeps +// its buffers between frames and allocates nothing after the first. package upscale import ( @@ -26,6 +38,8 @@ import ( "fmt" "image" "image/color" + "runtime" + "sync" ) // ErrorBound is the maximum absolute difference, on a 0..1 colour scale, @@ -38,13 +52,18 @@ import ( const ErrorBound = 2e-4 // Hard limits, checked before any allocation. They keep every size -// computation inside 32 bits of headroom and bound memory to a few hundred -// megabytes at the limit. +// computation inside 32 bits of headroom and bound memory: at the limit, +// about 0.5 GB of source planes, 0.5 GB of output and, per worker, the rows +// counted at MaxWorkers (0.7 GB for 64 workers at the widest output). const ( MaxSourcePixels = 1 << 25 // 33.5 Mpx (8192 x 4096) MaxOutputPixels = 1 << 27 // 134 Mpx (16384 x 8192) MaxDimension = 1 << 15 MaxScale = 4 + // MaxWorkers bounds Options.Workers: each worker owns about 90 rows of + // output-width floats (11 MB at the widest output), so the count is a + // memory bound too. + MaxWorkers = 64 ) // Errors returned by Upscale. @@ -52,6 +71,7 @@ var ( ErrNilImage = errors.New("upscale: nil image") ErrSize = errors.New("upscale: invalid size") ErrSharp = errors.New("upscale: invalid sharpness") + ErrDst = errors.New("upscale: destination buffer does not hold its rectangle") ) // Options configures Upscale. @@ -60,9 +80,15 @@ type Options struct { // sharpness, each +1 halves it. A negative value disables RCAS. FSR // integrations commonly use 0.2. Sharpness float32 + // Workers is the number of goroutines a frame is shared between, as + // bands of rows. Zero or less means runtime.GOMAXPROCS(0); values above + // MaxWorkers, or above the number of output rows, are lowered to it. + // The output does not depend on it. + Workers int } -// DefaultOptions returns RCAS enabled at 0.2 stops of attenuation. +// DefaultOptions returns RCAS enabled at 0.2 stops of attenuation, on +// GOMAXPROCS workers. func DefaultOptions() *Options { return &Options{Sharpness: 0.2} } // padding of the clamped source planes: EASU reads x-1..x+2 and y-1..y+2 @@ -80,6 +106,7 @@ type planes struct { r, g, b, l []float32 a []float32 // nil when the image is opaque tapOff [12]int // buffer offsets of the 12 EASU taps from "f" + gen uint32 // counts the pictures loaded: a cache of rows is keyed by it } func (p *planes) at(x, y int) int { return (y+padLo)*p.stride + x + padLo } @@ -131,22 +158,34 @@ func newPlanes(w, h int, alpha bool) *planes { return p } -// finish computes luma and replicates the borders (clamp to edge). -func (p *planes) finish() { - pl := [][]float32{p.r, p.g, p.b, p.l} - if p.a != nil { - pl = append(pl, p.a) +// all lists the planes, alpha last when there is one. +func (p *planes) all() (pl [5][]float32, n int) { + pl = [5][]float32{p.r, p.g, p.b, p.l, p.a} + if p.a == nil { + return pl, 4 } - for y := 0; y < p.h; y++ { - o := p.at(0, y) - for x := 0; x < p.w; x++ { - i := o + x - p.l[i] = p.b[i]*0.5 + (p.r[i]*0.5 + p.g[i]) - } + return pl, 5 +} + +// lumaRowFn computes the FSR luma of one row. Halving is exact, so the vector +// kernel that replaces it under GOEXPERIMENT=simd gives the same bits. +var lumaRowFn = lumaRow + +func lumaRow(l, r, g, b []float32) { + for x := range l { + l[x] = b[x]*0.5 + (r[x]*0.5 + g[x]) } - for _, s := range pl { - for y := 0; y < p.h; y++ { - o := p.at(0, y) +} + +// finishRows computes the luma of rows y0..y1-1 and replicates their left +// and right borders (clamp to edge). Rows are independent of one another. +func (p *planes) finishRows(y0, y1 int) { + pl, n := p.all() + for y := y0; y < y1; y++ { + o := p.at(0, y) + r, g, b, l := p.r[o:o+p.w], p.g[o:o+p.w], p.b[o:o+p.w], p.l[o:o+p.w] + lumaRowFn(l, r, g, b) + for _, s := range pl[:n] { for i := 1; i <= padLo; i++ { s[o-i] = s[o] } @@ -154,6 +193,14 @@ func (p *planes) finish() { s[o+p.w+i] = s[o+p.w-1] } } + } +} + +// padRows replicates the first and last rows into the top and bottom +// borders, once every row is finished, and marks the planes as a new picture. +func (p *planes) padRows() { + pl, n := p.all() + for _, s := range pl[:n] { row := p.at(-padLo, 0) for i := 1; i <= padLo; i++ { copy(s[row-i*p.stride:row-i*p.stride+p.stride], s[row:row+p.stride]) @@ -163,15 +210,40 @@ func (p *planes) finish() { copy(s[last+i*p.stride:last+i*p.stride+p.stride], s[last:last+p.stride]) } } + p.gen++ +} + +// finish completes planes whose colour (and alpha) were written directly. +func (p *planes) finish() { + p.finishRows(0, p.h) + p.padRows() +} + +// srcKind reports whether src needs an alpha plane, and whether its rows may +// be read by several goroutines at once (the image types of the standard +// library; an arbitrary image.Image is read by one). +func srcKind(src image.Image) (alpha, concurrent bool) { + switch m := src.(type) { + case *image.YCbCr, *image.Gray: + return false, true + case *image.RGBA: + return !m.Opaque(), true + case *image.NRGBA: + return !m.Opaque(), true + } + if o, ok := src.(interface{ Opaque() bool }); ok { + return !o.Opaque(), false + } + return true, false } -// fromImage converts src to planes. Opaque images take no alpha plane. -func fromImage(src image.Image) *planes { +// convert fills rows y0..y1-1 of the planes from src, whose size is theirs, +// and finishes them. Bands of rows may be converted concurrently. +func (p *planes) convert(src image.Image, y0, y1 int) { b := src.Bounds() - w, h := b.Dx(), b.Dy() + w := p.w switch m := src.(type) { case *image.YCbCr: - p := newPlanes(w, h, false) sx := 0 // horizontal chroma subsampling shift switch m.SubsampleRatio { case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420: @@ -179,41 +251,46 @@ func fromImage(src image.Image) *planes { case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410: sx = 2 } - for y := 0; y < h; y++ { + for y := y0; y < y1; y++ { o := p.at(0, y) yy := b.Min.Y + y yr := m.Y[m.YOffset(b.Min.X, yy):][:w] - co, c0 := m.COffset(b.Min.X, yy), b.Min.X>>sx - cb, cr := m.Cb[co:], m.Cr[co:] - pr, pg, pb := p.r[o:o+w], p.g[o:o+w], p.b[o:o+w] - for x, yv := range yr { - ci := (b.Min.X+x)>>sx - c0 - r, g, bl := ycc(yv, cb[ci], cr[ci]) - pr[x], pg[x], pb[x] = lut8[r], lut8[g], lut8[bl] - } + co := m.COffset(b.Min.X, yy) + yccRowFn(p.r[o:o+w], p.g[o:o+w], p.b[o:o+w], yr, m.Cb[co:], m.Cr[co:], b.Min.X, sx) } - p.finish() - return p case *image.RGBA: - return fromRGBA(m, w, h, b) + for y := y0; y < y1; y++ { + o := p.at(0, y) + s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] + for x := 0; x < w; x++ { + r, g, bl, a := s[4*x], s[4*x+1], s[4*x+2], s[4*x+3] + switch { + case p.a == nil || a == 255: + p.r[o+x], p.g[o+x], p.b[o+x] = lut8[r], lut8[g], lut8[bl] + case a > 0: // un-premultiply + f := 1 / float32(a) + p.r[o+x], p.g[o+x], p.b[o+x] = min(float32(r)*f, 1), min(float32(g)*f, 1), min(float32(bl)*f, 1) + default: // the planes are reused: a transparent pixel is written too + p.r[o+x], p.g[o+x], p.b[o+x] = 0, 0, 0 + } + if p.a != nil { + p.a[o+x] = lut8[a] + } + } + } case *image.NRGBA: - opaque := m.Opaque() - p := newPlanes(w, h, !opaque) - for y := 0; y < h; y++ { + for y := y0; y < y1; y++ { o := p.at(0, y) s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] for x := 0; x < w; x++ { p.r[o+x], p.g[o+x], p.b[o+x] = lut8[s[4*x]], lut8[s[4*x+1]], lut8[s[4*x+2]] - if !opaque { + if p.a != nil { p.a[o+x] = lut8[s[4*x+3]] } } } - p.finish() - return p case *image.Gray: - p := newPlanes(w, h, false) - for y := 0; y < h; y++ { + for y := y0; y < y1; y++ { o := p.at(0, y) s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] for x := 0; x < w; x++ { @@ -221,29 +298,34 @@ func fromImage(src image.Image) *planes { p.r[o+x], p.g[o+x], p.b[o+x] = v, v, v } } - p.finish() - return p - } - // Generic path through the colour model (slow, any image.Image). - opaque := true - if o, ok := src.(interface{ Opaque() bool }); ok { - opaque = o.Opaque() - } else { - opaque = false - } - p := newPlanes(w, h, !opaque) - for y := 0; y < h; y++ { - o := p.at(0, y) - for x := 0; x < w; x++ { - c := color.NRGBAModel.Convert(src.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA) - p.r[o+x], p.g[o+x], p.b[o+x] = lut8[c.R], lut8[c.G], lut8[c.B] - if !opaque { - p.a[o+x] = lut8[c.A] + default: + // Generic path through the colour model (slow, any image.Image). + for y := y0; y < y1; y++ { + o := p.at(0, y) + for x := 0; x < w; x++ { + c := color.NRGBAModel.Convert(src.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA) + p.r[o+x], p.g[o+x], p.b[o+x] = lut8[c.R], lut8[c.G], lut8[c.B] + if p.a != nil { + p.a[o+x] = lut8[c.A] + } } } } - p.finish() - return p + p.finishRows(y0, y1) +} + +// yccRowFn converts one row of Y'CbCr to planar float RGB. x0 is the image +// column of yr[0] and sx the horizontal chroma shift; cb and cr start at the +// chroma sample of column x0. +var yccRowFn = yccRow + +func yccRow(pr, pg, pb []float32, yr, cb, cr []uint8, x0, sx int) { + c0 := x0 >> sx + for x, yv := range yr { + ci := (x0+x)>>sx - c0 + r, g, bl := ycc(yv, cb[ci], cr[ci]) + pr[x], pg[x], pb[x] = lut8[r], lut8[g], lut8[bl] + } } // ycc is color.YCbCrToRGB (same integer arithmetic), small enough to inline. @@ -260,63 +342,167 @@ func clip8(v int32) uint8 { return uint8(^(v >> 31)) } -func fromRGBA(m *image.RGBA, w, h int, b image.Rectangle) *planes { - opaque := m.Opaque() - p := newPlanes(w, h, !opaque) - for y := 0; y < h; y++ { - o := p.at(0, y) - s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] - for x := 0; x < w; x++ { - r, g, bl, a := s[4*x], s[4*x+1], s[4*x+2], s[4*x+3] - if opaque || a == 255 { - p.r[o+x], p.g[o+x], p.b[o+x] = lut8[r], lut8[g], lut8[bl] - } else if a > 0 { // un-premultiply - f := 1 / float32(a) - p.r[o+x], p.g[o+x], p.b[o+x] = min(float32(r)*f, 1), min(float32(g)*f, 1), min(float32(bl)*f, 1) - } - if !opaque { - p.a[o+x] = lut8[a] - } - } - } - p.finish() - return p -} - // Upscale scales src to w x h (each at least the source size and at most // MaxScale times it) with EASU, then sharpens with RCAS unless // opt.Sharpness < 0. A nil opt means DefaultOptions. The result is an // *image.RGBA with origin (0, 0); it is opaque when src is. +// +// For a stream of frames, a Scaler does the same without allocating. func Upscale(src image.Image, w, h int, opt *Options) (*image.RGBA, error) { if src == nil { return nil, ErrNilImage } + s := NewScaler(opt) + if err := s.check(src, w, h); err != nil { + return nil, err + } + dst := image.NewRGBA(image.Rect(0, 0, w, h)) + s.upscale(dst, src) + return dst, nil +} + +// Scaler upscales frame after frame. It keeps every buffer it needs for the +// last geometry it saw (source size, output size, with or without alpha), so +// that a stream of same-sized frames allocates nothing after the first. +// +// A Scaler is for one goroutine at a time; it starts and joins its own +// workers inside Upscale and holds none between calls. +type Scaler struct { + opt Options + + f *frame + alpha bool + workers int // as asked for the cached frame: GOMAXPROCS may change + + // The picture being processed, for the workers. + src image.Image + dst *image.RGBA + converting bool + active int + jobs []func() + emitFn emitFn + wg sync.WaitGroup +} + +// NewScaler returns a Scaler with the given options; nil means +// DefaultOptions. The options are copied. +func NewScaler(opt *Options) *Scaler { if opt == nil { opt = DefaultOptions() } + s := &Scaler{opt: *opt} + s.emitFn = s.emit + return s +} + +// check refuses, before anything is allocated, what cannot be scaled: a +// source or an output outside the limits, a sharpness that is not a number. +func (s *Scaler) check(src image.Image, ow, oh int) error { sb := src.Bounds() - if err := checkSizes(sb.Dx(), sb.Dy(), w, h); err != nil { - return nil, err + if err := checkSizes(sb.Dx(), sb.Dy(), ow, oh); err != nil { + return err } - if opt.Sharpness != opt.Sharpness || opt.Sharpness > 64 { - return nil, ErrSharp + if s.opt.Sharpness != s.opt.Sharpness || s.opt.Sharpness > 64 { + return ErrSharp } - p := fromImage(src) - dst := image.NewRGBA(image.Rect(0, 0, w, h)) - run(p, w, h, opt.Sharpness, func(y int, r, g, b, a []float32) { - o := dst.PixOffset(0, y) - d := dst.Pix[o : o+4*w : o+4*w] - if a == nil { - packOpaqueFn(d, r[:w], g[:w], b[:w]) - return - } - for x := 0; x < w; x++ { - al := q8(a[x]) - f := float32(al) * (1.0 / 255) - d[4*x], d[4*x+1], d[4*x+2], d[4*x+3] = q8(r[x]*f), q8(g[x]*f), q8(b[x]*f), al + return nil +} + +// workerCount is the number of bands for oh output rows. +func workerCount(asked, oh int) int { + if asked <= 0 { + asked = runtime.GOMAXPROCS(0) + } + return min(asked, MaxWorkers, oh) +} + +// Upscale scales src to the size of dst and writes the result into dst, +// which is opaque when src is. The limits are those of the package-level +// Upscale. dst must not share memory with src. +func (s *Scaler) Upscale(dst *image.RGBA, src image.Image) error { + if src == nil || dst == nil { + return ErrNilImage + } + ow, oh := dst.Rect.Dx(), dst.Rect.Dy() + if err := s.check(src, ow, oh); err != nil { + return err + } + // A hand-built dst may state a rectangle its buffer does not hold, or a + // stride under a row: the bands would write outside it, or over one + // another, from goroutines whose panic nobody can recover. + if dst.Stride < 4*ow || int64(len(dst.Pix)) < int64(oh-1)*int64(dst.Stride)+int64(4*ow) { + return ErrDst + } + s.upscale(dst, src) + return nil +} + +// upscale is Upscale once the picture has been checked. +func (s *Scaler) upscale(dst *image.RGBA, src image.Image) { + sb, db := src.Bounds(), dst.Bounds() + sw, sh, ow, oh := sb.Dx(), sb.Dy(), db.Dx(), db.Dy() + alpha, concurrent := srcKind(src) + n := workerCount(s.opt.Workers, oh) + if f := s.f; f == nil || f.p.w != sw || f.p.h != sh || f.ow != ow || f.oh != oh || s.alpha != alpha || s.workers != n { + s.f, s.alpha, s.workers = newFrame(newPlanes(sw, sh, alpha), ow, oh, n), alpha, n + s.jobs = make([]func(), n) + for i := range s.jobs { + s.jobs[i] = func() { s.job(i) } } - }) - return dst, nil + } + s.src, s.dst = src, dst + s.converting = true + if concurrent { + s.fork(n) + } else { + s.fork(1) + } + s.f.p.padRows() + s.converting = false + s.fork(n) + s.src, s.dst = nil, nil +} + +// fork runs the current phase on n workers, the caller being the first, and +// waits for them. +func (s *Scaler) fork(n int) { + s.active = n + s.wg.Add(n - 1) + for i := 1; i < n; i++ { + go s.jobs[i]() + } + s.jobs[0]() + s.wg.Wait() +} + +// job is worker i's share of the current phase: a band of source rows to +// convert, or a band of output rows to compute. +func (s *Scaler) job(i int) { + f, n := s.f, s.active + if s.converting { + f.p.convert(s.src, f.p.h*i/n, f.p.h*(i+1)/n) + } else { + f.band(f.wk[i], f.oh*i/n, f.oh*(i+1)/n, s.opt.Sharpness, s.emitFn) + } + if i > 0 { + s.wg.Done() + } +} + +// emit writes one finished row into the destination. +func (s *Scaler) emit(y int, r, g, b, a []float32) { + dst, w := s.dst, s.f.ow + o := dst.PixOffset(dst.Rect.Min.X, dst.Rect.Min.Y+y) + d := dst.Pix[o : o+4*w : o+4*w] + if a == nil { + packOpaqueFn(d, r[:w], g[:w], b[:w]) + return + } + for x := 0; x < w; x++ { + al := q8(a[x]) + f := float32(al) * (1.0 / 255) + d[4*x], d[4*x+1], d[4*x+2], d[4*x+3] = q8(r[x]*f), q8(g[x]*f), q8(b[x]*f), al + } } // packOpaqueFn converts one row of opaque float pixels to RGBA bytes: the diff --git a/upscale/upscale_test.go b/upscale/upscale_test.go index cb545b1..2e30a81 100644 --- a/upscale/upscale_test.go +++ b/upscale/upscale_test.go @@ -107,8 +107,10 @@ func TestLimits(t *testing.T) { {0, 10}, {10, -1}, {9, 10}, {10, 9}, {41, 40}, {1<<31 - 1, 10}, {1 << 30, 1 << 30}, {1 << 16, 10}, } for _, c := range cases { + // Fatal, and the small cases first: once a size check is gone, the + // cases after it would really allocate what they ask for. if _, err := Upscale(src, c.w, c.h, nil); !errors.Is(err, ErrSize) { - t.Errorf("%dx%d: err = %v", c.w, c.h, err) + t.Fatalf("%dx%d: err = %v", c.w, c.h, err) } } if _, err := Upscale(nil, 20, 20, nil); !errors.Is(err, ErrNilImage) {