diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1329d46..905558b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -148,6 +148,36 @@ jobs: - name: Test + 100% coverage gate run: go test -race -coverprofile=cover.out ./... && go run . cover.out + # upscale/gpu is a module of its own (Metal and Vulkan bindings). A runner has + # no GPU, so its device tests skip, visibly (go test -v prints each SKIP); what + # runs everywhere is the shader compile, the fake-device tests of the Vulkan + # sequencing, and the build on the two platforms that have a backend. + gpu: + name: upscale/gpu (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + defaults: + run: + working-directory: upscale/gpu + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7 + with: + go-version: '1.27.4' + - name: gofmt + run: | + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then + echo "::error::these files are not gofmt-clean:"; echo "$unformatted" + exit 1 + fi + - run: go build ./... + - run: go vet ./... + - run: go test -v -count=1 ./... + # The media module on 32-bit. A job of its own on Linux, not a step guarded by # `if: runner.os` in the matrix above: buildscan reads that step as a 32-bit # build on every OS of the matrix, including darwin/386, which does not exist. diff --git a/upscale/gpu/bench_test.go b/upscale/gpu/bench_test.go new file mode 100644 index 0000000..5e30db7 --- /dev/null +++ b/upscale/gpu/bench_test.go @@ -0,0 +1,53 @@ +package gpu + +import ( + "image" + "testing" + + "github.com/go-avkit/avkit/upscale" +) + +// benchSrc is upscale's benchmark source: 4:2:0 YCbCr. +func benchSrc(w, h int) *image.YCbCr { + m := image.NewYCbCr(image.Rect(0, 0, w, h), image.YCbCrSubsampleRatio420) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + m.Y[y*m.YStride+x] = uint8(x*3 + y*5 + (x*y)>>6) + } + } + for i := range m.Cb { + m.Cb[i], m.Cr[i] = uint8(i), uint8(255-i) + } + return m +} + +// BenchmarkGPU720to1080 is a 1280x720 YCbCr 4:2:0 frame to 1920x1080 RGBA at +// sharpness 0.2, on the GPU. "frame" is everything Upscale does (conversion +// and upload, both kernels, readback into dst); "dispatch" is the two kernels +// and the wait alone, on a frame already uploaded. +func BenchmarkGPU720to1080(b *testing.B) { + s := openOrSkip(b, &upscale.Options{Sharpness: 0.2}) + defer s.Close() + src := benchSrc(1280, 720) + dst := image.NewRGBA(image.Rect(0, 0, 1920, 1080)) + if err := s.Upscale(dst, src); err != nil { // the first frame allocates + b.Fatal(err) + } + b.Run("frame", func(b *testing.B) { + b.SetBytes(1920 * 1080) + for b.Loop() { + if err := s.Upscale(dst, src); err != nil { + b.Fatal(err) + } + } + }) + b.Run("dispatch", func(b *testing.B) { + p := s.params(1280, 720, 1920, 1080, false) + b.SetBytes(1920 * 1080) + for b.Loop() { + if err := s.b.run(&p); err != nil { + b.Fatal(err) + } + } + }) +} diff --git a/upscale/gpu/fake_test.go b/upscale/gpu/fake_test.go new file mode 100644 index 0000000..2d40fb4 --- /dev/null +++ b/upscale/gpu/fake_test.go @@ -0,0 +1,437 @@ +package gpu + +import ( + "bytes" + "errors" + "image" + "image/color" + "math" + "strings" + "testing" + + "github.com/go-avkit/avkit/upscale" + "github.com/go-macos/metal" +) + +// fake is a backend that runs no kernel: it records what the Scaler asks of +// it, so that the host side is tested on machines without a GPU. +type fake struct { + setupErr, runErr error + setups, runs, closes int + sb, ob []byte + p params + floatOut bool +} + +func (f *fake) name() string { return "fake" } +func (f *fake) setup(sw, sh, ow, oh int, fo bool) error { + f.setups++ + if f.setupErr != nil { + return f.setupErr + } + f.sb = make([]byte, 4*sw*sh) + n := 4 * ow * oh + if fo { + n *= 4 + } + f.ob, f.floatOut = make([]byte, n), fo + return nil +} +func (f *fake) src() []byte { return f.sb } +func (f *fake) out() []byte { return f.ob } +func (f *fake) run(p *params) error { + f.runs++ + f.p = *p + if f.runErr != nil { + return f.runErr + } + for i := range f.ob { + f.ob[i] = byte(i*7 + 1) + } + return nil +} +func (f *fake) close() { f.closes++ } + +func newFake(t *testing.T, opt *upscale.Options) (*Scaler, *fake) { + t.Helper() + f := &fake{} + if opt == nil { + opt = upscale.DefaultOptions() + } + return newScaler(f, opt), f +} + +func TestFakeCopiesRowsIntoTheDestination(t *testing.T) { + s, f := newFake(t, nil) + big := image.NewRGBA(image.Rect(0, 0, 40, 30)) + for i := range big.Pix { + big.Pix[i] = 0xEE + } + dst := big.SubImage(image.Rect(3, 2, 3+14, 2+9)).(*image.RGBA) + if err := s.Upscale(dst, testRGBA("edges", 7, 5, 1)); err != nil { + t.Fatal(err) + } + for y := 0; y < 30; y++ { + for x := 0; x < 40; x++ { + o := big.PixOffset(x, y) + in := x >= 3 && x < 17 && y >= 2 && y < 11 + for c := 0; c < 4; c++ { + want := byte(0xEE) + if in { + want = f.ob[((y-2)*14+(x-3))*4+c] + } + if big.Pix[o+c] != want { + t.Fatalf("pixel (%d,%d) byte %d = %#x, want %#x (inside: %v)", x, y, c, big.Pix[o+c], want, in) + } + } + } + } +} + +func TestFakeParams(t *testing.T) { + src := testRGBA("noise", 30, 20, 1) + cases := []struct { + sharp float32 + rcas uint32 + k float32 + }{{0.2, 1, float32(math.Exp2(-0.2))}, {-1, 0, 1}, {0, 1, 1}, {64, 1, float32(math.Exp2(-64))}} + for _, c := range cases { + s, f := newFake(t, &upscale.Options{Sharpness: c.sharp}) + if err := s.Upscale(image.NewRGBA(image.Rect(0, 0, 45, 31)), src); err != nil { + t.Fatal(err) + } + sx, ox := axis(30, 45) + sy, oy := axis(20, 31) + want := params{SW: 30, SH: 20, OW: 45, OH: 31, SX: sx, OX: ox, SY: sy, OY: oy, K: c.k, RCAS: c.rcas} + if f.p != want { + t.Errorf("sharpness %v: params %+v, want %+v", c.sharp, f.p, want) + } + } + // The axis constants are FsrEasuCon's: output sample i at i*scale+off. + if sc, off := axis(1280, 1920); sc != float32(1280)/1920 || off != 0.5*float32(1280)*(1/float32(1920))-0.5 { + t.Errorf("axis(1280,1920) = %v, %v", sc, off) + } + if sc, off := axis(10, 10); sc != 1 || off != 0 { + t.Errorf("identity axis = %v, %v, want 1, 0", sc, off) + } +} + +func TestFakeBufferReuseAndGeometry(t *testing.T) { + s, f := newFake(t, nil) + a, b := testRGBA("noise", 10, 10, 1), testRGBA("noise", 12, 10, 1) + steps := []struct { + src *image.RGBA + ow, oh int + float bool + setups int + comment string + }{ + {a, 20, 20, false, 1, "first frame sets up"}, + {a, 20, 20, false, 1, "same geometry reuses the buffers"}, + {a, 30, 20, false, 2, "another output width"}, + {a, 30, 25, false, 3, "another output height"}, + {b, 30, 25, false, 4, "another source width"}, + {b, 30, 25, true, 5, "float output"}, + {b, 30, 25, true, 5, "float output again"}, + } + for _, st := range steps { + if err := s.prepare(st.ow, st.oh, st.src, st.float); err != nil { + t.Fatal(err) + } + if f.setups != st.setups { + t.Fatalf("%s: %d setups, want %d", st.comment, f.setups, st.setups) + } + if f.floatOut != st.float || f.p.Mode != map[bool]uint32{false: 0, true: 1}[st.float] { + t.Fatalf("%s: float output %v, mode %d", st.comment, f.floatOut, f.p.Mode) + } + } + // A source of the same width and another height is another geometry too. + if err := s.prepare(30, 25, testRGBA("noise", 12, 11, 1), true); err != nil { + t.Fatal(err) + } + if f.setups != 6 { + t.Fatalf("another source height: %d setups, want 6", f.setups) + } +} + +func TestFakeFailures(t *testing.T) { + s, f := newFake(t, nil) + dst := image.NewRGBA(image.Rect(0, 0, 20, 20)) + src := testRGBA("noise", 10, 10, 1) + boom := errors.New("boom") + f.setupErr = boom + refuses(t, "setup failure", boom, func() error { return s.Upscale(dst, src) }) + if f.runs != 0 { + t.Fatal("kernels ran after a failed setup") + } + f.setupErr = nil + refuses(t, "frame after a failed setup", nil, func() error { return s.Upscale(dst, src) }) + if f.setups != 2 || f.runs != 1 { + t.Fatalf("after a failed setup the next frame sets up again: setups %d, runs %d", f.setups, f.runs) + } + f.runErr = boom + if err := s.Upscale(dst, src); !errors.Is(err, boom) { + t.Fatalf("run failure: %v", err) + } +} + +func TestFakeClose(t *testing.T) { + s, f := newFake(t, nil) + s.Close() + s.Close() + if f.closes != 1 { + t.Fatalf("backend closed %d times, want 1", f.closes) + } + if err := s.Upscale(image.NewRGBA(image.Rect(0, 0, 20, 20)), testRGBA("noise", 10, 10, 1)); !errors.Is(err, ErrClosed) { + t.Fatalf("after Close: %v", err) + } + if f.setups != 0 || f.runs != 0 { + t.Fatal("a closed Scaler touched its backend") + } +} + +// refuses runs fn and reports whether it returned err, treating a panic as a +// failure of its own. +func refuses(t *testing.T, what string, want error, fn func() error) { + t.Helper() + defer func() { + if r := recover(); r != nil { + t.Errorf("%s: raised a runtime error instead of an error value: %v", what, r) + } + }() + if err := fn(); !errors.Is(err, want) { + t.Errorf("%s: %v, want %v", what, err, want) + } +} + +func TestFakeNilArguments(t *testing.T) { + s, _ := newFake(t, nil) + dst := image.NewRGBA(image.Rect(0, 0, 20, 20)) + src := testRGBA("noise", 10, 10, 1) + refuses(t, "nil source", upscale.ErrNilImage, func() error { return s.Upscale(dst, nil) }) + refuses(t, "nil destination", upscale.ErrNilImage, func() error { return s.Upscale(nil, src) }) +} + +func TestCheckSizes(t *testing.T) { + const D = upscale.MaxDimension + cases := []struct { + sw, sh, ow, oh int + want string // "" for accepted, else a substring of the error + }{ + {10, 10, 20, 20, ""}, + {10, 10, 40, 40, ""}, + {10, 10, 10, 10, ""}, + {0, 10, 20, 20, "=upscale: invalid size: 0x10 -> 20x20"}, + {10, 0, 20, 20, "=upscale: invalid size: 10x0 -> 20x20"}, + {10, 10, 0, 20, "=upscale: invalid size: 10x10 -> 0x20"}, + {10, 10, 20, 0, "=upscale: invalid size: 10x10 -> 20x0"}, + {-1, 10, 20, 20, "=upscale: invalid size: -1x10 -> 20x20"}, + {D + 1, 1, 100, 100, "dimension above"}, + {1, D + 1, 100, 100, "dimension above"}, + {10000, 10, D + 1, 100, "dimension above"}, + {10, 10000, 100, D + 1, "dimension above"}, + {30000, 30000, 100, 100, "too many pixels"}, + {3000, 3000, 12000, 12000, "too many pixels"}, + {8192, 4096, 16384, 8192, ""}, + {1, 1, 40, 40, "scale above"}, + {10, 10, 20, 40, ""}, + {10, 10, 41, 40, "scale above"}, + {10, 10, 40, 41, "scale above"}, + {10, 10, 9, 20, "would downscale"}, + {10, 10, 20, 9, "would downscale"}, + } + for _, c := range cases { + err := checkSizes(c.sw, c.sh, c.ow, c.oh) + if c.want == "" { + if err != nil { + t.Errorf("%dx%d -> %dx%d: %v, want accepted", c.sw, c.sh, c.ow, c.oh, err) + } + continue + } + if exact, ok := strings.CutPrefix(c.want, "="); ok { + if err == nil || err.Error() != exact { + t.Errorf("%dx%d -> %dx%d: %v, want %q", c.sw, c.sh, c.ow, c.oh, err, exact) + } + continue + } + if !errors.Is(err, upscale.ErrSize) || !strings.Contains(err.Error(), c.want) { + t.Errorf("%dx%d -> %dx%d: %v, want ErrSize with %q", c.sw, c.sh, c.ow, c.oh, err, c.want) + } + } +} + +func TestSharpnessLimit(t *testing.T) { + old := openBackendFn + defer func() { openBackendFn = old }() + openBackendFn = func() (backend, error) { return &fake{}, nil } + for _, c := range []struct { + v float32 + fail bool + }{{64, false}, {65, true}, {-1, false}, {float32(math.NaN()), true}} { + s, err := OpenOptions(&upscale.Options{Sharpness: c.v}) + if c.fail != errors.Is(err, upscale.ErrSharp) { + t.Errorf("sharpness %v: %v", c.v, err) + } + if s != nil { + s.Close() + } + } + s, err := Open() + if err != nil || s.opt.Sharpness != 0.2 { + t.Fatalf("Open: %v, %+v", err, s) + } +} + +func TestOpenPropagatesBackendError(t *testing.T) { + old := openBackendFn + defer func() { openBackendFn = old }() + boom := errors.New("boom") + openBackendFn = func() (backend, error) { return nil, boom } + if s, err := Open(); !errors.Is(err, boom) || s != nil { + t.Fatalf("Open: %v, %v", s, err) + } + openBackendFn = openBackend + if s, err := Open(); err == nil { + s.Close() + } else if !errors.Is(err, ErrUnsupported) { + t.Fatalf("the real backend's refusal is not ErrUnsupported: %v", err) + } +} + +func TestAlphaRefusal(t *testing.T) { + s, f := newFake(t, nil) + dst := image.NewRGBA(image.Rect(0, 0, 20, 20)) + opaqueSrc := testRGBA("noise", 10, 10, 1) + if err := s.Upscale(dst, opaqueSrc); err != nil { + t.Fatal(err) + } + n := image.NewNRGBA(image.Rect(0, 0, 10, 10)) + for i := 3; i < len(n.Pix); i += 4 { + n.Pix[i] = 255 + } + if err := s.Upscale(dst, n); err != nil { + t.Fatalf("opaque NRGBA: %v", err) + } + n.Pix[43] = 254 + runs := f.runs + refuses(t, "NRGBA with one translucent pixel", ErrAlpha, func() error { return s.Upscale(dst, n) }) + pal := image.NewPaletted(image.Rect(0, 0, 10, 10), color.Palette{color.RGBA{1, 2, 3, 255}, color.RGBA{0, 0, 0, 0}}) + pal.SetColorIndex(1, 1, 1) + refuses(t, "paletted with a transparent entry in use", ErrAlpha, func() error { return s.Upscale(dst, pal) }) + refuses(t, "image that cannot say it is opaque", ErrAlpha, func() error { return s.Upscale(dst, noOpaque{opaqueSrc}) }) + if f.runs != runs { + t.Fatal("kernels ran for a refused source") + } +} + +// noOpaque hides the Opaque method of an image. +type noOpaque struct{ m *image.RGBA } + +func (n noOpaque) ColorModel() color.Model { return n.m.ColorModel() } +func (n noOpaque) Bounds() image.Rectangle { return n.m.Bounds() } +func (n noOpaque) At(x, y int) color.Color { return n.m.At(x, y) } + +func TestPackSources(t *testing.T) { + rgba := testRGBA("noise", 13, 9, 5) + sub := rgba.SubImage(image.Rect(2, 3, 11, 8)).(*image.RGBA) + nrgba := image.NewNRGBA(image.Rect(0, 0, 13, 9)) + gray := image.NewGray(image.Rect(0, 0, 13, 9)) + for i := range nrgba.Pix { + nrgba.Pix[i] = byte(i * 31) + if i%4 == 3 { + nrgba.Pix[i] = 255 + } + } + for i := range gray.Pix { + gray.Pix[i] = byte(i * 17) + } + pal := image.NewPaletted(image.Rect(0, 0, 13, 9), color.Palette{color.RGBA{10, 20, 30, 255}, color.RGBA{200, 100, 50, 255}}) + for i := range pal.Pix { + pal.Pix[i] = uint8(i & 1) + } + images := map[string]image.Image{ + "rgba": rgba, "rgba subimage": sub, "nrgba": nrgba, "nrgba subimage": nrgba.SubImage(image.Rect(1, 1, 12, 8)), + "gray": gray, "gray subimage": gray.SubImage(image.Rect(3, 2, 10, 9)), "paletted": pal, "noOpaque": noOpaque{rgba}, + } + for _, r := range []image.YCbCrSubsampleRatio{image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420, + image.YCbCrSubsampleRatio440, image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410} { + m := image.NewYCbCr(image.Rect(0, 0, 13, 9), r) + for i := range m.Y { + m.Y[i] = byte(i * 13) + } + for i := range m.Cb { + m.Cb[i], m.Cr[i] = byte(i*29+3), byte(255-i*11) + } + images["ycbcr "+r.String()] = m + images["ycbcr subimage "+r.String()] = m.SubImage(image.Rect(3, 2, 12, 8)) + } + for name, img := range images { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + got := make([]byte, 4*w*h) + pack(got, img, w, h) + want := make([]byte, 0, len(got)) + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + c := color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA) + want = append(want, c.R, c.G, c.B, 255) + } + } + if !bytes.Equal(got, want) { + t.Errorf("%s: packed bytes differ from the colour model's", name) + } + } +} + +func TestYCCMatchesTheStandardLibrary(t *testing.T) { + for y := 0; y < 256; y += 5 { + for cb := 0; cb < 256; cb += 3 { + for cr := 0; cr < 256; cr += 3 { + r, g, b := ycc(uint8(y), uint8(cb), uint8(cr)) + wr, wg, wb := color.YCbCrToRGB(uint8(y), uint8(cb), uint8(cr)) + if r != wr || g != wg || b != wb { + t.Fatalf("ycc(%d,%d,%d) = %d,%d,%d, want %d,%d,%d", y, cb, cr, r, g, b, wr, wg, wb) + } + } + } + } +} + +func TestParamsLayout(t *testing.T) { + if n := len(paramBytes(¶ms{})); n != 48 { + t.Fatalf("params is %d bytes, the kernels expect 48", n) + } + p := params{SW: 1, SH: 2, OW: 3, OH: 4, SX: 1, K: 1, RCAS: 7, Mode: 9} + b := paramBytes(&p) + if b[0] != 1 || b[4] != 2 || b[8] != 3 || b[12] != 4 || b[28] != 0 || b[32+3] != 0x3f || b[36] != 7 || b[40] != 9 { + t.Fatalf("params bytes %v", b) + } + f := []float32{1, 2.5} + if g := floatsOf(unsafeBytes(f)); len(g) != 2 || g[1] != 2.5 { + t.Fatalf("floatsOf: %v", g) + } +} + +func unsafeBytes(f []float32) []byte { + b := make([]byte, 0, 4*len(f)) + for _, v := range f { + u := math.Float32bits(v) + b = append(b, byte(u), byte(u>>8), byte(u>>16), byte(u>>24)) + } + return b +} + +func TestMetalOpenErrors(t *testing.T) { + old := metalDefault + defer func() { metalDefault = old }() + for _, c := range []struct { + err error + unsupported bool + }{{metal.ErrUnsupported, true}, {metal.ErrNoDevice, true}, {errors.New("other"), false}} { + metalDefault = func() (*metal.Device, error) { return nil, c.err } + b, err := openMetal() + if b != nil || err == nil || errors.Is(err, ErrUnsupported) != c.unsupported { + t.Errorf("Default fails with %v: backend %v, error %v", c.err, b, err) + } + } +} diff --git a/upscale/gpu/go.mod b/upscale/gpu/go.mod new file mode 100644 index 0000000..25b049d --- /dev/null +++ b/upscale/gpu/go.mod @@ -0,0 +1,15 @@ +module github.com/go-avkit/avkit/upscale/gpu + +go 1.27.4 + +require ( + github.com/go-avkit/avkit v0.25.0 + github.com/go-gfx/vulkan v0.3.0 + github.com/go-gfx/wgsl v0.9.0 + github.com/go-macos/metal v0.8.0 +) + +require ( + github.com/ebitengine/purego v0.11.3 // indirect + github.com/go-macos/objc v0.12.0 // indirect +) diff --git a/upscale/gpu/go.sum b/upscale/gpu/go.sum new file mode 100644 index 0000000..a547db6 --- /dev/null +++ b/upscale/gpu/go.sum @@ -0,0 +1,12 @@ +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/go-avkit/avkit v0.25.0 h1:RCo7psX/IzdmhZmaFZWk1P9sbbHbatUBzS3AGeSkoUQ= +github.com/go-avkit/avkit v0.25.0/go.mod h1:pbhVWTLr7DinNK3UDF02NLynycH1EW8Ne5Knn0X4BpY= +github.com/go-gfx/vulkan v0.3.0 h1:k4/VbDn49+1asefS9XhLQLH7GB2l0Hk4BctbbR6YY6E= +github.com/go-gfx/vulkan v0.3.0/go.mod h1:IYZuEIwS3vtystKZRIp+DtuPWX3Nfq86yMC4gJ5ebhw= +github.com/go-gfx/wgsl v0.9.0 h1:6luCFFUwJOPpdkLYGnUOMl2Por2YTb/0bDLdJdpaFtw= +github.com/go-gfx/wgsl v0.9.0/go.mod h1:Fzzw0jXvB+zxCqmTDwvcu3B7PkIVJBcygl2dyDyDAgQ= +github.com/go-macos/metal v0.8.0 h1:BWv+rlHEwvbBwFtHuZzLvnjoqb14hvIftmHMhWP4MOA= +github.com/go-macos/metal v0.8.0/go.mod h1:BiclSGJgONDekug12CQtlINic9zMmXF7m/iA7bQn4hM= +github.com/go-macos/objc v0.12.0 h1:/WmB4C1CQd5RkqBRvnHNljEFtOTvytPA9fkD87xuJVQ= +github.com/go-macos/objc v0.12.0/go.mod h1:ao+SmTFBrkZdP+488hFTrSFvCtJ36McKKhNNOlcFXrQ= diff --git a/upscale/gpu/gpu.go b/upscale/gpu/gpu.go new file mode 100644 index 0000000..c21c6b8 --- /dev/null +++ b/upscale/gpu/gpu.go @@ -0,0 +1,306 @@ +// Package gpu runs FSR 1.0 (EASU followed by RCAS, as package upscale does on +// the CPU) on the graphics processor: Metal on macOS (go-macos/metal) and +// Vulkan on Linux (go-gfx/vulkan). It is a separate module because the root +// module's CI runners have no GPU. +// +// The arithmetic is that of upscale in 32-bit float, FSR's bit-trick rcp and +// rsqrt included. The result is held to upscale.ErrorBound of the float64 +// oracle (upscale/fsrref) by the tests, on the float result before 8-bit +// quantisation, which a test can read back (the bytes alone could only be +// held to half a level, 2e-3). +// +// Sources must be opaque: an image with transparent pixels is refused with +// ErrAlpha. The limits are those of upscale.Upscale. +package gpu + +import ( + "errors" + "fmt" + "image" + "image/color" + "math" + "unsafe" + + "github.com/go-avkit/avkit/upscale" + "github.com/go-avkit/avkit/upscale/fsrref" +) + +// ErrUnsupported is returned (wrapped) by Open when no GPU backend can run: +// the platform has none, or the machine has no device. +var ErrUnsupported = errors.New("gpu: no GPU backend available") + +// ErrAlpha is returned for a source with transparent pixels. +var ErrAlpha = errors.New("gpu: sources with an alpha channel are not supported") + +// ErrClosed is returned by a Scaler after Close. +var ErrClosed = errors.New("gpu: scaler closed") + +// params is the constant block of both kernels (48 bytes, the same layout in +// MSL and in WGSL). +type params struct { + SW, SH, OW, OH uint32 + SX, OX, SY, OY float32 // sample position of output i: i*S + O + K float32 // RCAS scale, 2^-sharpness + RCAS, Mode uint32 // Mode 0: packed RGBA8; 1: four float32 per pixel + _ uint32 +} + +// backend is one GPU API. +type backend interface { + name() string + // setup allocates the buffers of a geometry. Output is sized for mode. + setup(sw, sh, ow, oh int, floatOut bool) error + // src is the packed RGBA8 source (sw*sh*4 bytes) to fill. + src() []byte + // run executes both kernels and waits. + run(p *params) error + // out is the result of the last run. + out() []byte + close() +} + +// Scaler upscales frame after frame on the GPU, keeping its buffers between +// frames of the same geometry. It is for one goroutine at a time. +type Scaler struct { + opt upscale.Options + b backend + sw, sh int + ow, oh int + floatOut bool + set bool + closed bool +} + +// Open returns a Scaler with upscale.DefaultOptions on the platform's GPU +// backend. It returns an error wrapping ErrUnsupported when there is none. +func Open() (*Scaler, error) { return OpenOptions(nil) } + +// OpenOptions is Open with the given options (nil means the defaults). +// Options.Workers is ignored. +func OpenOptions(opt *upscale.Options) (*Scaler, error) { + if opt == nil { + opt = upscale.DefaultOptions() + } + if opt.Sharpness != opt.Sharpness || opt.Sharpness > 64 { + return nil, upscale.ErrSharp + } + b, err := openBackendFn() + if err != nil { + return nil, err + } + return newScaler(b, opt), nil +} + +func newScaler(b backend, opt *upscale.Options) *Scaler { return &Scaler{opt: *opt, b: b} } + +// Backend names the API in use ("metal" or "vulkan") and the device. +func (s *Scaler) Backend() string { return s.b.name() } + +// Close releases the GPU resources. It is safe to call twice. +func (s *Scaler) Close() { + if s.closed { + return + } + s.closed = true + s.b.close() +} + +func checkSizes(sw, sh, ow, oh int) error { + if sw <= 0 || sh <= 0 || ow <= 0 || oh <= 0 { + return fmt.Errorf("%w: %dx%d -> %dx%d", upscale.ErrSize, sw, sh, ow, oh) + } + if sw > upscale.MaxDimension || sh > upscale.MaxDimension || ow > upscale.MaxDimension || oh > upscale.MaxDimension { + return fmt.Errorf("%w: dimension above %d", upscale.ErrSize, upscale.MaxDimension) + } + if int64(sw)*int64(sh) > upscale.MaxSourcePixels || int64(ow)*int64(oh) > upscale.MaxOutputPixels { + return fmt.Errorf("%w: too many pixels", upscale.ErrSize) + } + if ow < sw || oh < sh { + return fmt.Errorf("%w: %dx%d -> %dx%d would downscale", upscale.ErrSize, sw, sh, ow, oh) + } + if int64(ow) > int64(sw)*upscale.MaxScale || int64(oh) > int64(sh)*upscale.MaxScale { + return fmt.Errorf("%w: scale above %dx", upscale.ErrSize, upscale.MaxScale) + } + return nil +} + +// opaque reports whether src has no transparent pixel; an image type that +// cannot say is taken as not. +func opaque(src image.Image) bool { + o, ok := src.(interface{ Opaque() bool }) + return ok && o.Opaque() +} + +// Upscale scales src to the size of dst and writes the result into dst, with +// the semantics of upscale.Scaler.Upscale. dst must not share memory with src. +func (s *Scaler) Upscale(dst *image.RGBA, src image.Image) error { + if s.closed { + return ErrClosed + } + if src == nil || dst == nil { + return upscale.ErrNilImage + } + if err := s.prepare(dst.Rect.Dx(), dst.Rect.Dy(), src, false); err != nil { + return err + } + out := s.b.out() + w := 4 * s.ow + for y := 0; y < s.oh; y++ { + o := dst.PixOffset(dst.Rect.Min.X, dst.Rect.Min.Y+y) + copy(dst.Pix[o:o+w], out[y*w:(y+1)*w]) + } + return nil +} + +// prepare converts src into the backend's buffer and runs the kernels; with +// floatOut the result is four float32 per pixel instead of RGBA8. +func (s *Scaler) prepare(ow, oh int, src image.Image, floatOut bool) error { + sb := src.Bounds() + sw, sh := sb.Dx(), sb.Dy() + if err := checkSizes(sw, sh, ow, oh); err != nil { + return err + } + if !opaque(src) { + return ErrAlpha + } + if !s.set || s.sw != sw || s.sh != sh || s.ow != ow || s.oh != oh || s.floatOut != floatOut { + if err := s.b.setup(sw, sh, ow, oh, floatOut); err != nil { + s.set = false + return err + } + s.sw, s.sh, s.ow, s.oh, s.floatOut, s.set = sw, sh, ow, oh, floatOut, true + } + pack(s.b.src(), src, sw, sh) + p := s.params(sw, sh, ow, oh, floatOut) + return s.b.run(&p) +} + +// params is the constant block of a frame of this geometry. +func (s *Scaler) params(sw, sh, ow, oh int, floatOut bool) params { + p := params{SW: uint32(sw), SH: uint32(sh), OW: uint32(ow), OH: uint32(oh), K: 1} + p.SX, p.OX = axis(sw, ow) + p.SY, p.OY = axis(sh, oh) + if s.opt.Sharpness >= 0 { + p.RCAS = 1 + p.K = float32(math.Exp2(float64(-s.opt.Sharpness))) + } + if floatOut { + p.Mode = 1 + } + return p +} + +// phaseTable is the source position of every output column then every output +// row, as float32 pairs (floor, fraction), from fsrref.Phase: exact in +// integers on the host, because computed in floats the position is an exact +// integer for odd:odd reduced ratios and the floor is then decided by rounding. +// Column x is at pair x, row y at pair ow+y. +func phaseTable(sw, sh, ow, oh int) []float32 { + t := make([]float32, 0, 2*(ow+oh)) + for _, a := range [2][2]int{{sw, ow}, {sh, oh}} { + for i := 0; i < a[1]; i++ { + f, num, den := fsrref.Phase(a[0], a[1], i) + t = append(t, float32(f), float32(float64(num)/float64(den))) + } + } + return t +} + +// axis is FsrEasuCon for one axis: output sample i is at i*scale+off. The +// kernels no longer read it (phaseTable replaced it); it stays in params. +func axis(in, out int) (scale, off float32) { + rcp := float32(1) / float32(out) + scale = float32(in) * rcp + off = 0.5*float32(in)*rcp - 0.5 + return +} + +// pack writes src as RGBA8 words, with the 8-bit conversions of package +// upscale (the JFIF integer arithmetic of image/color for YCbCr). +func pack(d []byte, src image.Image, w, h int) { + b := src.Bounds() + switch m := src.(type) { + case *image.YCbCr: + sx := 0 + switch m.SubsampleRatio { + case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420: + sx = 1 + case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410: + sx = 2 + } + for y := 0; y < h; y++ { + yy := b.Min.Y + y + yr := m.Y[m.YOffset(b.Min.X, yy):][:w] + co := m.COffset(b.Min.X, yy) + cb, cr := m.Cb[co:], m.Cr[co:] + row := d[4*y*w : 4*(y+1)*w] + c0 := b.Min.X >> sx + for x, yv := range yr { + ci := (b.Min.X+x)>>sx - c0 + r, g, bl := ycc(yv, cb[ci], cr[ci]) + row[4*x], row[4*x+1], row[4*x+2], row[4*x+3] = r, g, bl, 255 + } + } + case *image.RGBA: + for y := 0; y < h; y++ { + s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] + row := d[4*y*w : 4*(y+1)*w] + for x := 0; x < w; x++ { + row[4*x], row[4*x+1], row[4*x+2], row[4*x+3] = s[4*x], s[4*x+1], s[4*x+2], 255 + } + } + case *image.NRGBA: + for y := 0; y < h; y++ { + s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] + row := d[4*y*w : 4*(y+1)*w] + for x := 0; x < w; x++ { + row[4*x], row[4*x+1], row[4*x+2], row[4*x+3] = s[4*x], s[4*x+1], s[4*x+2], 255 + } + } + case *image.Gray: + for y := 0; y < h; y++ { + s := m.Pix[m.PixOffset(b.Min.X, b.Min.Y+y):] + row := d[4*y*w : 4*(y+1)*w] + for x := 0; x < w; x++ { + row[4*x], row[4*x+1], row[4*x+2], row[4*x+3] = s[x], s[x], s[x], 255 + } + } + default: + for y := 0; y < h; y++ { + row := d[4*y*w : 4*(y+1)*w] + for x := 0; x < w; x++ { + c := color.NRGBAModel.Convert(src.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA) + row[4*x], row[4*x+1], row[4*x+2], row[4*x+3] = c.R, c.G, c.B, 255 + } + } + } +} + +// ycc is color.YCbCrToRGB (same integer arithmetic). +func ycc(y, cb, cr uint8) (r, g, b uint8) { + yy1 := int32(y) * 0x10101 + cb1, cr1 := int32(cb)-128, int32(cr)-128 + return clip8(yy1 + 91881*cr1), clip8(yy1 - 22554*cb1 - 46802*cr1), clip8(yy1 + 116130*cb1) +} + +func clip8(v int32) uint8 { + if uint32(v)&0xff000000 == 0 { + return uint8(v >> 16) + } + return uint8(^(v >> 31)) +} + +// paramBytes views p as its 48 bytes. +func paramBytes(p *params) []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(p)), unsafe.Sizeof(*p)) +} + +// floatBytes views f as its bytes. +func floatBytes(f []float32) []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(f))), 4*len(f)) +} + +// floatsOf views b (four-byte aligned) as float32s. +func floatsOf(b []byte) []float32 { + return unsafe.Slice((*float32)(unsafe.Pointer(unsafe.SliceData(b))), len(b)/4) +} diff --git a/upscale/gpu/gpu_test.go b/upscale/gpu/gpu_test.go new file mode 100644 index 0000000..52134ae --- /dev/null +++ b/upscale/gpu/gpu_test.go @@ -0,0 +1,229 @@ +package gpu + +import ( + "errors" + "image" + "image/color" + "math" + "math/rand" + "os" + "testing" + + "github.com/go-avkit/avkit/upscale" + "github.com/go-avkit/avkit/upscale/fsrref" +) + +// openOrSkip opens a Scaler, or skips the test visibly when the machine has +// no GPU; with AVKIT_GPU_REQUIRE=1 a missing GPU is a failure. +func openOrSkip(t testing.TB, opt *upscale.Options) *Scaler { + t.Helper() + s, err := OpenOptions(opt) + if err != nil { + if errors.Is(err, ErrUnsupported) { + if os.Getenv("AVKIT_GPU_REQUIRE") == "1" { + t.Fatalf("AVKIT_GPU_REQUIRE=1 but there is no GPU backend: %v", err) + } + t.Skipf("SKIPPED: no GPU backend here (%v)", err) + } + t.Fatal(err) + } + t.Logf("backend: %s", s.Backend()) + t.Cleanup(s.Close) + return s +} + +func TestOpenWithoutGPUIsUnsupported(t *testing.T) { + s, err := Open() + if err != nil { + if !errors.Is(err, ErrUnsupported) { + t.Fatalf("Open without a GPU: %v, want an error wrapping ErrUnsupported", err) + } + t.Logf("no GPU backend: %v", err) + return + } + s.Close() +} + +func testRGBA(kind string, w, h int, seed int64) *image.RGBA { + rng := rand.New(rand.NewSource(seed)) + m := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + var r, g, b uint8 + switch kind { + case "noise": + r, g, b = uint8(rng.Intn(256)), uint8(rng.Intn(256)), uint8(rng.Intn(256)) + case "edges": + v := uint8(0) + if (x/5+y/7)%2 == 0 || (x-y)%9 == 0 { + v = 255 + } + r, g, b = v, v/2, 255-v + case "gradient": + r, g, b = uint8(x*255/max(w-1, 1)), uint8(y*255/max(h-1, 1)), uint8((x+y)&255) + case "black": + if x == w/2 && y == h/2 { + r = 200 + } + default: // white + r, g, b = 255, 255, 255 + if x == w/2 && y == h/2 { + g = 40 + } + } + m.SetRGBA(x, y, color.RGBA{r, g, b, 255}) + } + } + return m +} + +func toRef(m *image.RGBA) *fsrref.Image { + w, h := m.Rect.Dx(), m.Rect.Dy() + r := fsrref.New(w, h) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + o := m.PixOffset(x, y) + r.Pix[y*w+x] = [3]float64{float64(float32(m.Pix[o]) / 255), float64(float32(m.Pix[o+1]) / 255), float64(float32(m.Pix[o+2]) / 255)} + } + } + return r +} + +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 float result of the GPU, read back before the 8-bit +// quantisation, to upscale.ErrorBound of the float64 oracle. +func TestOracle(t *testing.T) { + worst, total, bad := 0.0, 0, 0 + for _, stop := range oracleStops { + s := openOrSkip(t, &upscale.Options{Sharpness: float32(stop)}) + for _, kind := range oracleKinds { + for _, sz := range oracleSizes { + src := testRGBA(kind, sz.sw, sz.sh, 7) + want := fsrref.Upscale(toRef(src), sz.ow, sz.oh, stop) + if err := s.prepare(sz.ow, sz.oh, src, true); err != nil { + t.Fatal(err) + } + got := floatsOf(s.b.out()) + for i := range want.Pix { + for q := 0; q < 3; q++ { + d := math.Abs(float64(got[4*i+q]) - want.Pix[i][q]) + total++ + if d > upscale.ErrorBound { + bad++ + if bad <= 8 { + t.Logf("%s %v stops=%v px %d ch %d: got %v want %v", kind, sz, stop, i, q, got[4*i+q], want.Pix[i][q]) + } + } + worst = math.Max(worst, d) + } + } + } + } + s.Close() + } + t.Logf("%s: max error %.3g over %d samples, %d above %g", "gpu", worst, total, bad, upscale.ErrorBound) + if bad != 0 { + t.Fatalf("%d samples exceed the error bound %g", bad, upscale.ErrorBound) + } +} + +// TestBytesAgainstCPU: the bytes of the GPU and of the CPU port agree to one +// level (the CPU result is itself within the bound of the oracle). +func TestBytesAgainstCPU(t *testing.T) { + s := openOrSkip(t, nil) + for _, kind := range oracleKinds { + for _, sz := range oracleSizes { + src := testRGBA(kind, sz.sw, sz.sh, 3) + want, err := upscale.Upscale(src, sz.ow, sz.oh, nil) + if err != nil { + t.Fatal(err) + } + got := image.NewRGBA(image.Rect(0, 0, sz.ow, sz.oh)) + if err := s.Upscale(got, src); err != nil { + t.Fatal(err) + } + far := 0 + for i := range want.Pix { + if d := int(want.Pix[i]) - int(got.Pix[i]); d > 1 || d < -1 { + far++ + } + } + // A quantisation edge may flip; two levels apart never. + if far != 0 { + t.Errorf("%s %v: %d bytes differ from the CPU result by more than one level", kind, sz, far) + } + } + } +} + +func TestYCbCrAgainstCPU(t *testing.T) { + s := openOrSkip(t, nil) + src := image.NewYCbCr(image.Rect(0, 0, 64, 36), image.YCbCrSubsampleRatio420) + rng := rand.New(rand.NewSource(1)) + for i := range src.Y { + src.Y[i] = uint8(rng.Intn(256)) + } + for i := range src.Cb { + src.Cb[i], src.Cr[i] = uint8(rng.Intn(256)), uint8(rng.Intn(256)) + } + want, err := upscale.Upscale(src, 96, 54, nil) + if err != nil { + t.Fatal(err) + } + got := image.NewRGBA(image.Rect(0, 0, 96, 54)) + if err := s.Upscale(got, src); err != nil { + t.Fatal(err) + } + for i := range want.Pix { + if d := int(want.Pix[i]) - int(got.Pix[i]); d > 1 || d < -1 { + t.Fatalf("byte %d: gpu %d cpu %d", i, got.Pix[i], want.Pix[i]) + } + } +} + +func TestRefusals(t *testing.T) { + s := openOrSkip(t, nil) + dst := image.NewRGBA(image.Rect(0, 0, 20, 20)) + if err := s.Upscale(dst, nil); !errors.Is(err, upscale.ErrNilImage) { + t.Errorf("nil source: %v", err) + } + if err := s.Upscale(nil, testRGBA("noise", 10, 10, 1)); !errors.Is(err, upscale.ErrNilImage) { + t.Errorf("nil destination: %v", err) + } + if err := s.Upscale(image.NewRGBA(image.Rect(0, 0, 5, 5)), testRGBA("noise", 10, 10, 1)); !errors.Is(err, upscale.ErrSize) { + t.Errorf("downscale: %v", err) + } + a := testRGBA("noise", 10, 10, 1) + a.Pix[3] = 10 + if err := s.Upscale(dst, a); !errors.Is(err, ErrAlpha) { + t.Errorf("alpha source: %v, want ErrAlpha", err) + } + s.Close() + s.Close() + if err := s.Upscale(dst, testRGBA("noise", 10, 10, 1)); !errors.Is(err, ErrClosed) { + t.Errorf("closed: %v", err) + } +} + +func TestBadSharpness(t *testing.T) { + if _, err := OpenOptions(&upscale.Options{Sharpness: float32(math.NaN())}); !errors.Is(err, upscale.ErrSharp) { + t.Errorf("NaN sharpness: %v", err) + } +} + +func TestGeometryChangeReusesScaler(t *testing.T) { + s := openOrSkip(t, nil) + for _, sz := range []pair{{20, 20, 30, 30}, {20, 20, 40, 40}, {30, 20, 30, 20}, {20, 20, 30, 30}} { + dst := image.NewRGBA(image.Rect(0, 0, sz.ow, sz.oh)) + if err := s.Upscale(dst, testRGBA("edges", sz.sw, sz.sh, 1)); err != nil { + t.Fatalf("%v: %v", sz, err) + } + } +} diff --git a/upscale/gpu/metal.go b/upscale/gpu/metal.go new file mode 100644 index 0000000..e9f84df --- /dev/null +++ b/upscale/gpu/metal.go @@ -0,0 +1,115 @@ +package gpu + +import ( + "errors" + "fmt" + + "github.com/go-macos/metal" +) + +type metalBackend struct { + dev *metal.Device + lib *metal.Library + easu, rcas *metal.Pipeline + srcB, eB *metal.Buffer + outB, phB *metal.Buffer + ow, oh int +} + +// metalDefault is replaced by the tests. +var metalDefault = metal.Default + +func openMetal() (backend, error) { return openMetalWith(mslSource, "easu", "rcas") } + +// openMetalWith compiles src and takes the two kernels by name. +func openMetalWith(src, easu, rcas string) (backend, error) { + dev, err := metalDefault() + if err != nil { + if errors.Is(err, metal.ErrUnsupported) || errors.Is(err, metal.ErrNoDevice) { + return nil, fmt.Errorf("%w: %v", ErrUnsupported, err) + } + return nil, err + } + b := &metalBackend{dev: dev} + if err = b.compile(src, easu, rcas); err != nil { + b.close() + return nil, err + } + return b, nil +} + +func (b *metalBackend) compile(src, easu, rcas string) (err error) { + if b.lib, err = b.dev.Compile(src); err != nil { + return err + } + if b.easu, err = b.lib.Pipeline(easu); err != nil { + return err + } + b.rcas, err = b.lib.Pipeline(rcas) + return err +} + +func (b *metalBackend) name() string { return "metal: " + b.dev.Name() } + +func (b *metalBackend) release() { + for _, buf := range []*metal.Buffer{b.srcB, b.eB, b.outB, b.phB} { + if buf != nil { + buf.Close() + } + } + b.srcB, b.eB, b.outB, b.phB = nil, nil, nil, nil +} + +func (b *metalBackend) setup(sw, sh, ow, oh int, floatOut bool) error { + b.release() + outPx := 4 + if floatOut { + outPx = 16 + } + for _, a := range []struct { + buf **metal.Buffer + size int + }{{&b.srcB, 4 * sw * sh}, {&b.eB, 16 * ow * oh}, {&b.outB, outPx * ow * oh}, {&b.phB, 8 * (ow + oh)}} { + var err error + if *a.buf, err = b.dev.NewBuffer(a.size); err != nil { + b.release() + return err + } + } + copy(b.phB.Bytes(), floatBytes(phaseTable(sw, sh, ow, oh))) + b.ow, b.oh = ow, oh + return nil +} + +func (b *metalBackend) src() []byte { return b.srcB.Bytes() } +func (b *metalBackend) out() []byte { return b.outB.Bytes() } + +func (b *metalBackend) run(p *params) error { + return b.dev.Run(func(e *metal.Encoder) { + e.Use(b.easu) + e.Buffer(0, b.srcB) + e.Buffer(1, b.eB) + metal.Constant(e, 2, p) + e.Buffer(3, b.phB) + e.Dispatch(b.ow, b.oh) + e.Use(b.rcas) + e.Buffer(0, b.eB) + e.Buffer(1, b.outB) + metal.Constant(e, 2, p) + e.Dispatch(b.ow, b.oh) + }) +} + +func (b *metalBackend) close() { + b.release() + if b.easu != nil { + b.easu.Close() + } + if b.rcas != nil { + b.rcas.Close() + } + if b.lib != nil { + b.lib.Close() + } + b.dev.Close() +} diff --git a/upscale/gpu/metal_test.go b/upscale/gpu/metal_test.go new file mode 100644 index 0000000..e513973 --- /dev/null +++ b/upscale/gpu/metal_test.go @@ -0,0 +1,57 @@ +package gpu + +import ( + "errors" + "strings" + "testing" +) + +// metalOrSkip opens the Metal backend with the given source and kernel names, +// or skips visibly when this machine has no Metal. +func metalOrSkip(t *testing.T, src, easu, rcas string) (backend, error) { + t.Helper() + b, err := openMetalWith(src, easu, rcas) + if errors.Is(err, ErrUnsupported) { + t.Skipf("SKIPPED: no Metal here (%v)", err) + } + return b, err +} + +func TestMetalRefusesBadSource(t *testing.T) { + b, err := metalOrSkip(t, "this is not Metal", "easu", "rcas") + if err == nil || b != nil { + t.Fatalf("a source that does not compile: %v, %v", b, err) + } + t.Logf("compiler said: %v", err) + if !strings.Contains(err.Error(), "error") { + t.Errorf("the compiler's own message is expected: %v", err) + } +} + +func TestMetalRefusesMissingKernels(t *testing.T) { + for _, c := range []struct{ easu, rcas string }{{"nope", "rcas"}, {"easu", "nope"}} { + b, err := metalOrSkip(t, mslSource, c.easu, c.rcas) + if err == nil || b != nil { + t.Errorf("kernels %q, %q: %v, %v", c.easu, c.rcas, b, err) + } + } +} + +func TestMetalRefusesAnImpossibleGeometry(t *testing.T) { + b, err := metalOrSkip(t, mslSource, "easu", "rcas") + if err != nil { + t.Fatal(err) + } + defer b.close() + // 4*sw*sh bytes, then 16*ow*oh twice: each of the three requests is too + // large for a buffer in turn. + for _, g := range [][4]int{{1 << 30, 1 << 30, 1, 1}, {1, 1, 1 << 30, 1 << 30}} { + if err := b.setup(g[0], g[1], g[2], g[3], true); err == nil { + t.Errorf("setup%v accepted", g) + } + } + // The backend still works afterwards. + if err := b.setup(4, 4, 8, 8, false); err != nil { + t.Fatal(err) + } +} diff --git a/upscale/gpu/msl.go b/upscale/gpu/msl.go new file mode 100644 index 0000000..65451e4 --- /dev/null +++ b/upscale/gpu/msl.go @@ -0,0 +1,179 @@ +package gpu + +// mslSource is FSR 1.0 EASU and RCAS (ffx_fsr1.h, 32-bit float path, +// Copyright (c) 2021 Advanced Micro Devices, Inc., MIT licence, see +// upscale/LICENSE-FSR1.txt) as two Metal compute kernels. It is the same +// arithmetic as upscale/easu.go and upscale/rcas.go, including the integer +// approximations of rcp and rsqrt, which are part of the definition. +// +// Fast math is switched off for the file: the bit tricks and the ordering of +// the operations are the definition. RCAS never relies on a NaN being ignored +// (the reference does, where a ring pixel is 0 or 1): the two ratios that are +// NaN there are replaced by "no candidate", which is the same value and +// survives a compiler that assumes there is no NaN. +const mslSource = ` +#include +using namespace metal; + +#pragma METAL fp math_mode(safe) +#pragma METAL fp contract(off) + +struct P { + uint sw, sh, ow, oh; + float sx, ox, sy, oy; + float k; + uint rcas, mode, pad; +}; + +inline float rcpLo(float a) { return as_type(0x7ef07ebbu - as_type(a)); } +inline float rsqLo(float a) { return as_type(0x5f347d74u - (as_type(a) >> 1)); } +inline float rcpMed(float a) { float b = as_type(0x7ef19fffu - as_type(a)); return b * (-b * a + 2.0f); } +inline float sat(float a) { return min(1.0f, max(0.0f, a)); } +inline float absf(float a) { return as_type(as_type(a) & 0x7fffffffu); } + +inline float3 load(device const uint *s, constant P &p, int x, int y) { + x = clamp(x, 0, int(p.sw) - 1); + y = clamp(y, 0, int(p.sh) - 1); + uint v = s[uint(y) * p.sw + uint(x)]; + return float3(float(v & 255u), float((v >> 8) & 255u), float((v >> 16) & 255u)) / 255.0f; +} + +inline float luma(float3 c) { return c.z * 0.5f + (c.x * 0.5f + c.y); } + +// easuSet returns the contributions (dirX, dirY, len) of one bilinear corner. +inline float3 easuSet(float w, float a, float b, float c, float d, float e) { + float lenX = rcpLo(max(absf(d - c), absf(c - b))); + float dx = d - b; + lenX = sat(absf(dx) * lenX); + lenX *= lenX; + float lenY = rcpLo(max(absf(e - c), absf(c - a))); + float dy = e - a; + lenY = sat(absf(dy) * lenY); + lenY *= lenY; + return float3(dx * w, dy * w, lenX * w + lenY * w); +} + +inline float easuTap(float offx, float offy, float dirx, float diry, float lx, float ly, float lob, float clp) { + float vx = (offx * dirx + offy * diry) * lx; + float vy = (offx * -diry + offy * dirx) * ly; + float d2 = min(vx * vx + vy * vy, clp); + float wB = 2.0f / 5.0f * d2 - 1.0f; + float wA = lob * d2 - 1.0f; + wB *= wB; + wA *= wA; + wB = 25.0f / 16.0f * wB - (25.0f / 16.0f - 1.0f); + return wB * wA; +} + +inline float3 clamp4(float3 v, float3 a, float3 b, float3 c, float3 d) { + float3 lo = min(min(a, b), min(c, d)), hi = max(max(a, b), max(c, d)); + return min(max(v, lo), hi); +} + +kernel void easu(device const uint *src [[buffer(0)]], device float4 *dst [[buffer(1)]], + constant P &p [[buffer(2)]], device const float *ph [[buffer(3)]], + uint2 id [[thread_position_in_grid]]) { + if (id.x >= p.ow || id.y >= p.oh) return; + // the position is a host table (phaseTable): floor and fraction, exact + float fpx = ph[2 * id.x], ppx = ph[2 * id.x + 1]; + float fpy = ph[2 * (p.ow + id.y)], ppy = ph[2 * (p.ow + id.y) + 1]; + int fx = int(fpx), fy = int(fpy); + + // b c / e f g h / i j k l / n o + float3 cB = load(src, p, fx, fy - 1), cC = load(src, p, fx + 1, fy - 1); + float3 cE = load(src, p, fx - 1, fy), cF = load(src, p, fx, fy); + float3 cG = load(src, p, fx + 1, fy), cH = load(src, p, fx + 2, fy); + float3 cI = load(src, p, fx - 1, fy + 1), cJ = load(src, p, fx, fy + 1); + float3 cK = load(src, p, fx + 1, fy + 1), cL = load(src, p, fx + 2, fy + 1); + float3 cN = load(src, p, fx, fy + 2), cO = load(src, p, fx + 1, fy + 2); + float lB = luma(cB), lC = luma(cC), lE = luma(cE), lF = luma(cF), lG = luma(cG), lH = luma(cH); + float lI = luma(cI), lJ = luma(cJ), lK = luma(cK), lL = luma(cL), lN = luma(cN), lO = luma(cO); + + float3 s = easuSet((1.0f - ppx) * (1.0f - ppy), lB, lE, lF, lG, lJ); + s += easuSet(ppx * (1.0f - ppy), lC, lF, lG, lH, lK); + s += easuSet((1.0f - ppx) * ppy, lF, lI, lJ, lK, lN); + s += easuSet(ppx * ppy, lG, lJ, lK, lL, lO); + float dirX = s.x, dirY = s.y, ln = s.z; + + float dirR = dirX * dirX + dirY * dirY; + if (dirR < 1.0f / 32768.0f) { + dirR = 1.0f; + dirX = 1.0f; + } else { + dirR = rsqLo(dirR); + } + dirX *= dirR; + dirY *= dirR; + ln *= 0.5f; + ln *= ln; + float stretch = (dirX * dirX + dirY * dirY) * rcpLo(max(absf(dirX), absf(dirY))); + float lx = 1.0f + (stretch - 1.0f) * ln; + float ly = 1.0f + -0.5f * ln; + float lob = 0.5f + ((1.0f / 4.0f - 0.04f) - 0.5f) * ln; + float clp = rcpLo(lob); + + // The reference's accumulation order: b c i j f e k l h g o n. + float3 a = float3(0.0f); + float aw = 0.0f; + float w; + w = easuTap(0.0f - ppx, -1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cB * w; aw += w; + w = easuTap(1.0f - ppx, -1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cC * w; aw += w; + w = easuTap(-1.0f - ppx, 1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cI * w; aw += w; + w = easuTap(0.0f - ppx, 1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cJ * w; aw += w; + w = easuTap(0.0f - ppx, 0.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cF * w; aw += w; + w = easuTap(-1.0f - ppx, 0.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cE * w; aw += w; + w = easuTap(1.0f - ppx, 1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cK * w; aw += w; + w = easuTap(2.0f - ppx, 1.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cL * w; aw += w; + w = easuTap(2.0f - ppx, 0.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cH * w; aw += w; + w = easuTap(1.0f - ppx, 0.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cG * w; aw += w; + w = easuTap(1.0f - ppx, 2.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cO * w; aw += w; + w = easuTap(0.0f - ppx, 2.0f - ppy, dirX, dirY, lx, ly, lob, clp); a += cN * w; aw += w; + float3 res = clamp4(a * (1.0f / aw), cF, cG, cJ, cK); + dst[id.y * p.ow + id.x] = float4(res, 0.0f); +} + +// lobeOf is the RCAS lobe candidate of one channel; a ratio the reference +// leaves NaN (and then ignores) is no candidate. +inline float lobeOf(float b, float d, float e, float f, float h) { + float mn4 = min(min(b, d), min(f, h)), mx4 = max(max(b, d), max(f, h)); + float hitMin = min(mn4, e) * (1.0f / (4.0f * mx4)); + float hitMax = (1.0f - max(mx4, e)) * (1.0f / (4.0f * mn4 - 4.0f)); + float cMin = mx4 > 0.0f ? -hitMin : -1.0e30f; + float cMax = mn4 < 1.0f ? hitMax : -1.0e30f; + return max(cMin, cMax); +} + +inline uint q8(float v) { + if (!(v > 0.0f)) return 0u; + return uint(min(v * 255.0f + 0.5f, 255.0f)); +} + +kernel void rcas(device const float4 *src [[buffer(0)]], device uint *dst [[buffer(1)]], + constant P &p [[buffer(2)]], uint2 id [[thread_position_in_grid]]) { + if (id.x >= p.ow || id.y >= p.oh) return; + uint x = id.x, y = id.y; + uint xl = x > 0 ? x - 1 : 0, xr = min(x + 1, p.ow - 1); + uint yu = y > 0 ? y - 1 : 0, yd = min(y + 1, p.oh - 1); + float3 e = src[y * p.ow + x].xyz; + float3 o = e; + if (p.rcas != 0) { + float3 b = src[yu * p.ow + x].xyz, d = src[y * p.ow + xl].xyz; + float3 f = src[y * p.ow + xr].xyz, h = src[yd * p.ow + x].xyz; + float lr = lobeOf(b.x, d.x, e.x, f.x, h.x); + float lg = lobeOf(b.y, d.y, e.y, f.y, h.y); + float lb = lobeOf(b.z, d.z, e.z, f.z, h.z); + float lobe = max(-(0.25f - 1.0f / 16.0f), min(max(max(lr, lg), lb), 0.0f)) * p.k; + float rcp = rcpMed(4.0f * lobe + 1.0f); + o = (lobe * b + lobe * d + lobe * h + lobe * f + e) * rcp; + } + uint i = y * p.ow + x; + if (p.mode == 0) { + dst[i] = q8(o.x) | (q8(o.y) << 8) | (q8(o.z) << 16) | (255u << 24); + } else { + dst[4 * i] = as_type(o.x); + dst[4 * i + 1] = as_type(o.y); + dst[4 * i + 2] = as_type(o.z); + dst[4 * i + 3] = 0; + } +} +` diff --git a/upscale/gpu/open.go b/upscale/gpu/open.go new file mode 100644 index 0000000..ae3e55a --- /dev/null +++ b/upscale/gpu/open.go @@ -0,0 +1,17 @@ +package gpu + +import "runtime" + +// openBackendFn is replaced by the tests. +var openBackendFn = openBackend + +// openBackend picks the platform's backend. +func openBackend() (backend, error) { + switch runtime.GOOS { + case "darwin": + return openMetal() + case "linux": + return openVulkan() + } + return nil, ErrUnsupported +} diff --git a/upscale/gpu/phase_test.go b/upscale/gpu/phase_test.go new file mode 100644 index 0000000..218314f --- /dev/null +++ b/upscale/gpu/phase_test.go @@ -0,0 +1,72 @@ +package gpu + +import ( + "image" + "math" + "testing" + + "github.com/go-avkit/avkit/upscale" + "github.com/go-avkit/avkit/upscale/fsrref" +) + +// TestPhaseTies is upscale's TestPhaseTies on the GPU: when the two sizes, +// reduced, are both odd, the source position of every other output sample is an +// integer, and a float floor picks a footprint one sample off on a saturated +// diagonal edge (0.064 measured). The kernels read the position from a table +// computed in integers; no sample may be outside upscale.ErrorBound. +func TestPhaseTies(t *testing.T) { + for _, stop := range []float64{-1, 0.2} { + s := openOrSkip(t, &upscale.Options{Sharpness: float32(stop)}) + for _, c := range []pair{{16, 16, 48, 48}, {21, 15, 35, 25}, {16, 16, 32, 32}, {9, 7, 15, 21}, {640, 8, 1920, 24}} { + src := image.NewRGBA(image.Rect(0, 0, c.sw, c.sh)) + 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 + } + o := src.PixOffset(x, y) + src.Pix[o], src.Pix[o+1], src.Pix[o+2], src.Pix[o+3] = v, 0, 255, 255 + } + } + want := fsrref.Upscale(toRef(src), c.ow, c.oh, stop) + if err := s.prepare(c.ow, c.oh, src, true); err != nil { + t.Fatal(err) + } + got := floatsOf(s.b.out()) + worst, outside := 0.0, 0 + for i := range want.Pix { + for q := 0; q < 3; q++ { + d := math.Abs(float64(got[4*i+q]) - want.Pix[i][q]) + worst = math.Max(worst, d) + if d > upscale.ErrorBound { + outside++ + } + } + } + t.Logf("stops %v %v: worst %.3g, %d of %d outside %g", stop, c, worst, outside, 3*len(want.Pix), upscale.ErrorBound) + if outside != 0 { + t.Errorf("stops %v %v: %d samples outside the bound, worst %g", stop, c, outside, worst) + } + } + s.Close() + } +} + +// TestPhaseTable: the table is fsrref.Phase, floor then fraction, columns then +// rows. +func TestPhaseTable(t *testing.T) { + tab := phaseTable(16, 9, 48, 21) + if len(tab) != 2*(48+21) { + t.Fatalf("%d entries", len(tab)) + } + for _, c := range []struct{ in, out, i, at int }{{16, 48, 0, 0}, {16, 48, 47, 47}, {9, 21, 0, 48}, {9, 21, 20, 48 + 20}} { + f, n, d := fsrref.Phase(c.in, c.out, c.i) + if tab[2*c.at] != float32(f) || tab[2*c.at+1] != float32(float64(n)/float64(d)) { + t.Errorf("%d->%d sample %d: %v %v, want %d %d/%d", c.in, c.out, c.i, tab[2*c.at], tab[2*c.at+1], f, n, d) + } + } + if tab[0] != -1 { + t.Errorf("first sample lies before the source: floor %v, want -1", tab[0]) + } +} diff --git a/upscale/gpu/vulkan.go b/upscale/gpu/vulkan.go new file mode 100644 index 0000000..34fa18f --- /dev/null +++ b/upscale/gpu/vulkan.go @@ -0,0 +1,262 @@ +package gpu + +import ( + "fmt" + "time" + + "github.com/go-gfx/vulkan" + "github.com/go-gfx/wgsl" + "github.com/go-gfx/wgsl/spirv" +) + +// frameTimeout bounds the wait for one frame's fence. +const frameTimeout = 30 * time.Second + +// group is the workgroup edge of wgslSource (@workgroup_size(8, 8, 1)). +const group = 8 + +// spirvOf compiles the two entry points of src to one SPIR-V module. +func spirvOf(src, easu, rcas string, rte bool) (w []uint32, err error) { + m, err := wgsl.Parse(src) + if err == nil { + info, errs := wgsl.Check(m) + if len(errs) > 0 { + err = fmt.Errorf("gpu: check WGSL: %w", errs) + } + if err == nil { + w, err = spirv.Module(m, info, spirv.Options{RoundingModeRTE: rte}, easu, rcas) + } + } + return w, err +} + +// tag wraps err with sentinel, and leaves nil alone. +func tag(sentinel, err error) (out error) { + if err != nil { + out = fmt.Errorf("%w: %w", sentinel, err) + } + return out +} + +// first runs the steps in order and stops at the first error. +func first(steps ...func() error) error { + for _, s := range steps { + if err := s(); err != nil { + return err + } + } + return nil +} + +// keep stores v in *dst unless err is set: a failed constructor may return a +// typed nil, which must not become a non-nil interface to close later. +func keep[T any](dst *T, v T, err error) error { + if err == nil { + *dst = v + } + return err +} + +// closer is a Vulkan object that can be released. +type closer interface{ Close() } + +// vkBuf is a buffer; a device-local one has no bytes. +type vkBuf interface { + closer + Bytes() []byte +} + +// vkFence is a submission to wait for. +type vkFence interface { + closer + Wait(time.Duration) (bool, error) +} + +// vkDev is the part of go-gfx/vulkan the backend uses, so that the sequencing +// and the cleanup after each failure can be tested without a device. The real +// one is realDev (vulkan_real.go); objects are passed back to the device that +// made them. +type vkDev interface { + NewBuffer(size uint64, u vulkan.BufferUsage) (vkBuf, error) + NewDeviceBuffer(size uint64, u vulkan.BufferUsage) (vkBuf, error) + NewReadbackBuffer(size uint64, u vulkan.BufferUsage) (vkBuf, error) + NewShader(words []uint32) (closer, error) + NewComputePipeline(sh closer, entry string, binds []vulkan.Binding) (closer, error) + Bind(p closer, binding uint32, b vkBuf) error + NewCommandBuffer() (closer, error) + Begin(c closer) error + Dispatch(c, p closer, x, y, z uint32) error + Barrier(c closer) error + End(c closer) error + Submit(c closer) (vkFence, error) + Name() string + RTE() bool + Close() +} + +type vulkanBackend struct { + dev vkDev + sh closer + easu, rcas closer + srcB vkBuf // host, written per frame + midB vkBuf // device-local, the EASU result + outB vkBuf // host-cached, read per frame + parB vkBuf // uniform, 48 bytes + phB vkBuf // phaseTable of the geometry + lutB vkBuf // float32(i)/255, kept for the scaler's life + ow, oh int +} + +func openVulkan() (backend, error) { return openVulkanWith(realOpen) } + +// openVulkanWith opens a device with open and builds the two pipelines. +func openVulkanWith(open func() (vkDev, error)) (backend, error) { + var out backend + dev, err := open() + err = tag(ErrUnsupported, err) + if err == nil { + b := &vulkanBackend{dev: dev} + if err = b.compile(wgslSource, "easu", "rcas"); err == nil { + out = b + } else { + b.close() + } + } + return out, err +} + +// bindings is the layout of both pipelines: wgslSource declares five buffers. +var bindings = []vulkan.Binding{ + {Binding: 0, Kind: vulkan.StorageBuffer}, + {Binding: 1, Kind: vulkan.StorageBuffer}, + {Binding: 2, Kind: vulkan.StorageBuffer}, + {Binding: 3, Kind: vulkan.UniformBuffer}, + {Binding: 4, Kind: vulkan.StorageBuffer}, + {Binding: 5, Kind: vulkan.StorageBuffer}, +} + +func (b *vulkanBackend) compile(src, easu, rcas string) error { + words, err := spirvOf(src, easu, rcas, b.dev.RTE()) + if err != nil { + return err + } + pipe := func(dst *closer, entry string) func() error { + return func() error { + p, e := b.dev.NewComputePipeline(b.sh, entry, bindings) + return keep(dst, p, e) + } + } + return first( + func() error { s, e := b.dev.NewShader(words); return keep(&b.sh, s, e) }, + pipe(&b.easu, easu), + pipe(&b.rcas, rcas), + b.buf(&b.lutB, b.dev.NewBuffer, 4*256, vulkan.UsageStorage), + func() error { copy(b.lutB.Bytes(), unitTable()); return nil }, + ) +} + +// unitTable is float32(i)/255 for i in 0..255 as bytes, rounded by Go. +func unitTable() []byte { + t := make([]float32, 256) + for i := range t { + t[i] = float32(i) / 255 + } + return floatBytes(t) +} + +func (b *vulkanBackend) name() string { return b.dev.Name() } + +// buf is the step that allocates a buffer of size bytes into *dst. +func (b *vulkanBackend) buf(dst *vkBuf, mk func(uint64, vulkan.BufferUsage) (vkBuf, error), size int, u vulkan.BufferUsage) func() error { + return func() error { + v, e := mk(uint64(size), u) + return keep(dst, v, e) + } +} + +func (b *vulkanBackend) release() { + for _, buf := range []*vkBuf{&b.srcB, &b.midB, &b.outB, &b.parB, &b.phB} { + if *buf != nil { + (*buf).Close() + *buf = nil + } + } +} + +// bindAll binds the five buffers to both pipelines. +func (b *vulkanBackend) bindAll() error { + var steps []func() error + for _, p := range []closer{b.easu, b.rcas} { + for i, buf := range []vkBuf{b.srcB, b.midB, b.outB, b.parB, b.lutB, b.phB} { + steps = append(steps, func() error { return b.dev.Bind(p, uint32(i), buf) }) + } + } + return first(steps...) +} + +func (b *vulkanBackend) setup(sw, sh, ow, oh int, floatOut bool) error { + b.release() + outPx := 4 + if floatOut { + outPx = 16 + } + err := first( + b.buf(&b.srcB, b.dev.NewBuffer, 4*sw*sh, vulkan.UsageStorage), + b.buf(&b.midB, b.dev.NewDeviceBuffer, 16*ow*oh, vulkan.UsageStorage), + b.buf(&b.outB, b.dev.NewReadbackBuffer, outPx*ow*oh, vulkan.UsageStorage), + b.buf(&b.parB, b.dev.NewBuffer, len(paramBytes(¶ms{})), vulkan.UsageUniform), + b.buf(&b.phB, b.dev.NewBuffer, 8*(ow+oh), vulkan.UsageStorage), + func() error { copy(b.phB.Bytes(), floatBytes(phaseTable(sw, sh, ow, oh))); return nil }, + b.bindAll, + ) + if err == nil { + b.ow, b.oh = ow, oh + } else { + b.release() + } + return err +} + +func (b *vulkanBackend) src() []byte { return b.srcB.Bytes() } +func (b *vulkanBackend) out() []byte { return b.outB.Bytes() } + +func (b *vulkanBackend) run(p *params) error { + copy(b.parB.Bytes(), paramBytes(p)) + var cb closer + var f vkFence + defer func() { + if cb != nil { + cb.Close() + } + if f != nil { + f.Close() + } + }() + gx, gy := uint32((b.ow+group-1)/group), uint32((b.oh+group-1)/group) + done := false + err := first( + func() error { c, e := b.dev.NewCommandBuffer(); return keep(&cb, c, e) }, + func() error { return b.dev.Begin(cb) }, + func() error { return b.dev.Dispatch(cb, b.easu, gx, gy, 1) }, + func() error { return b.dev.Barrier(cb) }, + func() error { return b.dev.Dispatch(cb, b.rcas, gx, gy, 1) }, + func() error { return b.dev.End(cb) }, + func() error { v, e := b.dev.Submit(cb); return keep(&f, v, e) }, + func() (e error) { done, e = f.Wait(frameTimeout); return }, + ) + if err == nil && !done { + err = fmt.Errorf("gpu: frame not finished after %v", frameTimeout) + } + return err +} + +func (b *vulkanBackend) close() { + b.release() + for _, c := range []closer{b.lutB, b.easu, b.rcas, b.sh} { + if c != nil { + c.Close() + } + } + b.lutB, b.easu, b.rcas, b.sh = nil, nil, nil, nil + b.dev.Close() +} diff --git a/upscale/gpu/vulkan_real.go b/upscale/gpu/vulkan_real.go new file mode 100644 index 0000000..90067bd --- /dev/null +++ b/upscale/gpu/vulkan_real.go @@ -0,0 +1,70 @@ +package gpu + +import ( + "fmt" + + "github.com/go-gfx/vulkan" +) + +// realDev is a go-gfx/vulkan device behind vkDev. The objects it hands out +// are the binding's own and come back to it, so the assertions below cannot +// fail for objects it made. +type realDev struct { + in *vulkan.Instance + d *vulkan.Device +} + +// realOpen opens the instance, the best physical device and a logical device. +func realOpen() (vkDev, error) { + var in *vulkan.Instance + var pd *vulkan.PhysicalDevice + var d *vulkan.Device + err := first( + func() (e error) { in, e = vulkan.Open(vulkan.Options{ApplicationName: "avkit"}); return }, + func() (e error) { pd, e = in.Pick(vulkan.Filter{}); return }, + func() (e error) { d, e = pd.Open(); return }, + ) + var out vkDev + if err == nil { + out = &realDev{in: in, d: d} + } else if in != nil { + in.Close() + } + return out, err +} + +func (r *realDev) NewBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return r.d.NewBuffer(n, u) +} +func (r *realDev) NewDeviceBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return r.d.NewDeviceBuffer(n, u) +} +func (r *realDev) NewReadbackBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return r.d.NewReadbackBuffer(n, u) +} +func (r *realDev) NewShader(w []uint32) (closer, error) { return r.d.NewShader(w) } +func (r *realDev) NewComputePipeline(sh closer, entry string, binds []vulkan.Binding) (closer, error) { + return r.d.NewComputePipeline(sh.(*vulkan.Shader), entry, binds) +} +func (r *realDev) Bind(p closer, binding uint32, b vkBuf) error { + return p.(*vulkan.Pipeline).Bind(binding, b.(*vulkan.Buffer)) +} +func (r *realDev) NewCommandBuffer() (closer, error) { return r.d.NewCommandBuffer() } +func (r *realDev) Begin(c closer) error { return c.(*vulkan.CommandBuffer).Begin() } +func (r *realDev) Dispatch(c, p closer, x, y, z uint32) error { + return c.(*vulkan.CommandBuffer).Dispatch(p.(*vulkan.Pipeline), x, y, z) +} +func (r *realDev) Barrier(c closer) error { return c.(*vulkan.CommandBuffer).Barrier() } +func (r *realDev) End(c closer) error { return c.(*vulkan.CommandBuffer).End() } +func (r *realDev) Submit(c closer) (vkFence, error) { + return r.d.Submit(c.(*vulkan.CommandBuffer)) +} +func (r *realDev) RTE() bool { return r.d.Info().RoundingModeRTEFloat32 } +func (r *realDev) Name() string { + i := r.d.Info() + return fmt.Sprintf("vulkan: %s (%s)", i.Name, i.DriverName) +} +func (r *realDev) Close() { + r.d.Close() + r.in.Close() +} diff --git a/upscale/gpu/vulkan_test.go b/upscale/gpu/vulkan_test.go new file mode 100644 index 0000000..4ab3883 --- /dev/null +++ b/upscale/gpu/vulkan_test.go @@ -0,0 +1,392 @@ +package gpu + +import ( + "bytes" + "errors" + "fmt" + "slices" + "testing" + "time" + + "github.com/go-gfx/vulkan" +) + +// TestShaderCompiles needs no device: the WGSL must parse, check and emit to +// SPIR-V (with and without the RTE mode) on every platform. +func TestShaderCompiles(t *testing.T) { + var n [2]int + for i, rte := range []bool{false, true} { + w, err := spirvOf(wgslSource, "easu", "rcas", rte) + if err != nil { + t.Fatalf("rte %v: %v", rte, err) + } + if len(w) < 100 || w[0] != 0x07230203 { + t.Fatalf("rte %v: %d words, magic %#x", rte, len(w), w[0]) + } + n[i] = len(w) + } + if n[1] <= n[0] { + t.Errorf("the RTE module (%d words) should add its capability and modes to the plain one (%d)", n[1], n[0]) + } +} + +func TestShaderErrors(t *testing.T) { + for name, src := range map[string]string{ + "syntax": "fn (", + "type": "@compute @workgroup_size(1) fn easu() { let x: u32 = 1.5; }", + "missing": "@compute @workgroup_size(1) fn other() {}", + } { + if _, err := spirvOf(src, "easu", "rcas", false); err == nil { + t.Errorf("%s: no error", name) + } + } +} + +func TestFirst(t *testing.T) { + var ran []int + step := func(i int, err error) func() error { + return func() error { ran = append(ran, i); return err } + } + bad := errors.New("bad") + if err := first(step(1, nil), step(2, bad), step(3, nil)); err != bad || !slices.Equal(ran, []int{1, 2}) { + t.Errorf("first: %v after %v, want bad after [1 2]", err, ran) + } + ran = nil + if err := first(step(1, nil), step(2, nil)); err != nil || !slices.Equal(ran, []int{1, 2}) { + t.Errorf("first all ok: %v after %v", err, ran) + } + if err := first(); err != nil { + t.Errorf("first of nothing: %v", err) + } +} + +func TestKeep(t *testing.T) { + v := 1 + if err := keep(&v, 2, errors.New("x")); err == nil || v != 1 { + t.Errorf("keep with an error stored %d (err %v)", v, err) + } + if err := keep(&v, 2, nil); err != nil || v != 2 { + t.Errorf("keep without an error: %d, %v", v, err) + } +} + +func TestUnitTable(t *testing.T) { + f := floatsOf(unitTable()) + if len(f) != 256 || f[0] != 0 || f[255] != 1 || f[51] != float32(51)/255 { + t.Errorf("table: %d entries, %v %v %v", len(f), f[0], f[255], f[51]) + } +} + +// TestRealOpenWithoutVulkan: where there is no Vulkan loader or device the +// open fails with an error, and nothing is left open. +func TestRealOpenWithoutVulkan(t *testing.T) { + d, err := realOpen() + if err == nil { + d.Close() + t.Skip("SKIPPED: a Vulkan device is here, the failure path cannot be seen") + } + if d != nil { + t.Errorf("realOpen failed (%v) but returned a device", err) + } +} + +// ---- a fake device ---- + +var errInjected = errors.New("injected") + +// fakeVK records every call and fails the failAt-th (1-based, 0 never). +type fakeVK struct { + ops, failAt int + live int // objects made and not closed + log []string + waitDone bool + rte bool + closed bool + bufs []*fakeObj + shaders [][]uint32 +} + +type fakeObj struct { + f *fakeVK + kind string + closed bool + data []byte + usage vulkan.BufferUsage + entry string + binds map[uint32]*fakeObj +} + +func (o *fakeObj) Close() { + if !o.closed { + o.closed = true + o.f.live-- + } +} +func (o *fakeObj) Bytes() []byte { return o.data } +func (o *fakeObj) Wait(d time.Duration) (bool, error) { + if err := o.f.step("wait"); err != nil { + return false, err + } + return o.f.waitDone, nil +} + +func (f *fakeVK) step(what string) error { + f.ops++ + f.log = append(f.log, what) + if f.ops == f.failAt { + return fmt.Errorf("%s: %w", what, errInjected) + } + return nil +} + +func (f *fakeVK) make(kind string, size int, u vulkan.BufferUsage) *fakeObj { + o := &fakeObj{f: f, kind: kind, usage: u, binds: map[uint32]*fakeObj{}} + if size > 0 { + o.data = make([]byte, size) + } + f.live++ + return o +} + +func (f *fakeVK) buffer(kind string, size uint64, u vulkan.BufferUsage) (vkBuf, error) { + if err := f.step(kind); err != nil { + return nil, err + } + o := f.make(kind, int(size), u) + f.bufs = append(f.bufs, o) + return o, nil +} + +func (f *fakeVK) NewBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return f.buffer("buffer", n, u) +} +func (f *fakeVK) NewDeviceBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return f.buffer("device buffer", n, u) +} +func (f *fakeVK) NewReadbackBuffer(n uint64, u vulkan.BufferUsage) (vkBuf, error) { + return f.buffer("readback buffer", n, u) +} +func (f *fakeVK) NewShader(w []uint32) (closer, error) { + if err := f.step("shader"); err != nil { + return nil, err + } + f.shaders = append(f.shaders, w) + return f.make("shader", 0, 0), nil +} +func (f *fakeVK) NewComputePipeline(sh closer, entry string, binds []vulkan.Binding) (closer, error) { + if err := f.step("pipeline " + entry); err != nil { + return nil, err + } + if sh.(*fakeObj).kind != "shader" { + return nil, errors.New("pipeline made from a " + sh.(*fakeObj).kind) + } + f.log = append(f.log, fmt.Sprint(binds)) + o := f.make("pipeline", 0, 0) + o.entry = entry + return o, nil +} +func (f *fakeVK) Bind(p closer, binding uint32, b vkBuf) error { + if err := f.step("bind"); err != nil { + return err + } + p.(*fakeObj).binds[binding] = b.(*fakeObj) + return nil +} +func (f *fakeVK) NewCommandBuffer() (closer, error) { + if err := f.step("command buffer"); err != nil { + return nil, err + } + return f.make("command", 0, 0), nil +} +func (f *fakeVK) Begin(c closer) error { return f.step("begin") } +func (f *fakeVK) Dispatch(c, p closer, x, y, z uint32) error { + return f.step(fmt.Sprintf("dispatch %s %d %d %d", p.(*fakeObj).entry, x, y, z)) +} +func (f *fakeVK) Barrier(c closer) error { return f.step("barrier") } +func (f *fakeVK) End(c closer) error { return f.step("end") } +func (f *fakeVK) Submit(c closer) (vkFence, error) { + if err := f.step("submit"); err != nil { + return nil, err + } + return f.make("fence", 0, 0), nil +} +func (f *fakeVK) Name() string { return "fake" } +func (f *fakeVK) RTE() bool { return f.rte } +func (f *fakeVK) Close() { f.closed = true } + +func (f *fakeVK) open() (vkDev, error) { + if err := f.step("open"); err != nil { + return nil, err + } + return f, nil +} + +func (f *fakeVK) count(what string) (n int) { + for _, l := range f.log { + if l == what { + n++ + } + } + return +} + +func TestVulkanSequence(t *testing.T) { + f := &fakeVK{waitDone: true, rte: true} + be, err := openVulkanWith(f.open) + if err != nil { + t.Fatal(err) + } + b := be.(*vulkanBackend) + if b.name() != "fake" { + t.Errorf("name %q", b.name()) + } + // the module was built for a device with RTE: longer than without + plain, _ := spirvOf(wgslSource, "easu", "rcas", false) + if len(f.shaders) != 1 || len(f.shaders[0]) <= len(plain) { + t.Errorf("shader of %d words (plain is %d): RTE not passed on", len(f.shaders[0]), len(plain)) + } + if f.count("pipeline easu") != 1 || f.count("pipeline rcas") != 1 { + t.Errorf("pipelines: %v", f.log) + } + if want := fmt.Sprint(bindings); f.count(want) != 2 { + t.Errorf("bindings %s used %d times, want 2", want, f.count(want)) + } + lut := f.bufs[0] + if lut.usage != vulkan.UsageStorage || len(lut.data) != 1024 || !bytes.Equal(lut.data, unitTable()) { + t.Errorf("table buffer: usage %v, %d bytes", lut.usage, len(lut.data)) + } + + if err := b.setup(1280, 720, 1920, 1080, false); err != nil { + t.Fatal(err) + } + // source, EASU result, output, parameters, phase table, in setup's order + wantSizes := []int{4 * 1280 * 720, 16 * 1920 * 1080, 4 * 1920 * 1080, 48, 8 * (1920 + 1080)} + if len(f.bufs) != 1+len(wantSizes) { + t.Fatalf("%d buffers made", len(f.bufs)) + } + for i, want := range wantSizes { + if got := len(f.bufs[1+i].data); got != want { + t.Errorf("buffer %d (%s): %d bytes, want %d", i, f.bufs[1+i].kind, got, want) + } + } + if !bytes.Equal(b.phB.Bytes(), floatBytes(phaseTable(1280, 720, 1920, 1080))) { + t.Error("phase table not filled") + } + if len(b.src()) != 4*1280*720 || len(b.out()) != 4*1920*1080 { + t.Errorf("src %d, out %d bytes", len(b.src()), len(b.out())) + } + if b.parB.(*fakeObj).usage != vulkan.UsageUniform || b.midB.(*fakeObj).usage != vulkan.UsageStorage { + t.Errorf("usages: params %v, mid %v", b.parB.(*fakeObj).usage, b.midB.(*fakeObj).usage) + } + for _, p := range []closer{b.easu, b.rcas} { + bound := p.(*fakeObj).binds + for i, want := range []vkBuf{b.srcB, b.midB, b.outB, b.parB, b.lutB, b.phB} { + if bound[uint32(i)] != want { + t.Errorf("%s binding %d is not the %d-th buffer", p.(*fakeObj).entry, i, i) + } + } + } + + f.log = nil + p := params{SW: 1280, SH: 720, OW: 1920, OH: 1080, K: 0.5} + if err := b.run(&p); err != nil { + t.Fatal(err) + } + want := []string{"command buffer", "begin", "dispatch easu 240 135 1", "barrier", "dispatch rcas 240 135 1", "end", "submit", "wait"} + if !slices.Equal(f.log, want) { + t.Errorf("run: %v, want %v", f.log, want) + } + if !bytes.Equal(b.parB.Bytes(), paramBytes(&p)) { + t.Errorf("params not copied: % x", b.parB.Bytes()) + } + // a geometry that is not a multiple of the workgroup rounds up + b.ow, b.oh = 17, 9 + f.log = nil + if err := b.run(&p); err != nil || f.log[2] != "dispatch easu 3 2 1" { + t.Errorf("rounding up: %v, %v", f.log, err) + } + + // a new geometry releases the old buffers + live := f.live + if err := b.setup(40, 30, 60, 45, true); err != nil { + t.Fatal(err) + } + if f.live != live || len(b.out()) != 16*60*45 { + t.Errorf("setup again: live %d (was %d), out %d bytes", f.live, live, len(b.out())) + } + b.close() + if f.live != 0 || !f.closed { + t.Errorf("after close: %d objects alive, device closed %v", f.live, f.closed) + } +} + +func TestVulkanWaitTimesOut(t *testing.T) { + f := &fakeVK{waitDone: false} + be, err := openVulkanWith(f.open) + if err != nil { + t.Fatal(err) + } + b := be.(*vulkanBackend) + defer b.close() + if err := b.setup(8, 8, 8, 8, false); err != nil { + t.Fatal(err) + } + if err := b.run(¶ms{}); err == nil { + t.Fatal("a frame the fence did not report done was accepted") + } + if f.live != 9 { // table, shader, 2 pipelines, 5 buffers: no command buffer or fence left + t.Errorf("live objects after a timed-out frame: %d, want 9", f.live) + } +} + +// TestVulkanFailsCleanly fails each operation of open, setup, run in turn: the +// error comes back, and once the backend is closed nothing is left alive. +func TestVulkanFailsCleanly(t *testing.T) { + seq := func(f *fakeVK) error { + be, err := openVulkanWith(f.open) + if err == nil { + b := be.(*vulkanBackend) + err = first( + func() error { return b.setup(20, 10, 30, 15, false) }, + func() error { return b.run(¶ms{}) }, + ) + b.close() + } + return err + } + probe := &fakeVK{waitDone: true} + if err := seq(probe); err != nil { + t.Fatal(err) + } + if probe.live != 0 { + t.Fatalf("a clean run leaves %d objects", probe.live) + } + for n := 1; n <= probe.ops; n++ { + f := &fakeVK{waitDone: true, failAt: n} + err := seq(f) + if !errors.Is(err, errInjected) { + t.Errorf("failing operation %d (%s): error %v", n, f.log[n-1], err) + } + if n == 1 && !errors.Is(err, ErrUnsupported) { + t.Errorf("a device that does not open is ErrUnsupported, got %v", err) + } + if n > 1 && errors.Is(err, ErrUnsupported) { + t.Errorf("operation %d (%s) failed after the device opened: not ErrUnsupported", n, f.log[n-1]) + } + if f.live != 0 { + t.Errorf("failing operation %d (%s): %d objects left alive", n, f.log[n-1], f.live) + } + if n > 1 && !f.closed { + t.Errorf("failing operation %d: device not closed", n) + } + } +} + +// TestVulkanCompileFailure: a shader that does not compile closes the device. +func TestVulkanCompileFailure(t *testing.T) { + f := &fakeVK{} + b := &vulkanBackend{dev: f} + if err := b.compile("fn (", "easu", "rcas"); err == nil || f.ops != 0 { + t.Errorf("compile of bad source: %v after %d device calls", err, f.ops) + } +} diff --git a/upscale/gpu/wgsl.go b/upscale/gpu/wgsl.go new file mode 100644 index 0000000..0ed973e --- /dev/null +++ b/upscale/gpu/wgsl.go @@ -0,0 +1,226 @@ +package gpu + +// wgslSource is FSR 1.0 EASU and RCAS (ffx_fsr1.h, 32-bit float path, +// Copyright (c) 2021 Advanced Micro Devices, Inc., MIT licence, see +// upscale/LICENSE-FSR1.txt) as two WGSL compute entry points, the same +// arithmetic as mslSource, compiled to SPIR-V by go-gfx/wgsl/spirv. The +// emitter marks every float operation NoContraction, so a driver cannot fuse +// or reassociate what the port orders by hand. +// +// The 8-bit samples are converted by a table of the 256 values float32(i)/255 +// (binding 4), filled on the host: a GPU's float division is not correctly +// rounded (Vulkan allows 2.5 ulp), and EASU turns one ulp of a luma into a +// visible difference where two lumas are nearly equal. +// +// The sample position of each output column and row is a host table (binding +// 5, phaseTable): its floor and fraction are computed in integers, exactly. +// +// All six buffers are declared for both entry points (the pipelines bind the +// same six), and the only subset constructs used are the ones docs/SPIRV.md +// of go-gfx/wgsl lists: no local arrays, no vector comparisons, no pointers. +const wgslSource = ` +struct P { + sw: u32, sh: u32, ow: u32, oh: u32, + sx: f32, ox: f32, sy: f32, oy: f32, + k: f32, + rcas: u32, mode: u32, pad: u32, +} + +@group(0) @binding(0) var src: array; +@group(0) @binding(1) var mid: array>; +@group(0) @binding(2) var dst: array; +@group(0) @binding(3) var p: P; +@group(0) @binding(4) var lut: array; +@group(0) @binding(5) var ph: array; + +fn rcpLo(a: f32) -> f32 { return bitcast(0x7ef07ebbu - bitcast(a)); } +fn rsqLo(a: f32) -> f32 { return bitcast(0x5f347d74u - (bitcast(a) >> 1u)); } +fn rcpMed(a: f32) -> f32 { + let b = bitcast(0x7ef19fffu - bitcast(a)); + return b * (-b * a + 2.0); +} +fn sat(a: f32) -> f32 { return min(1.0, max(0.0, a)); } + +fn load(x: i32, y: i32) -> vec3 { + let cx = clamp(x, 0, i32(p.sw) - 1); + let cy = clamp(y, 0, i32(p.sh) - 1); + let v = src[u32(cy) * p.sw + u32(cx)]; + return vec3(lut[v & 255u], lut[(v >> 8u) & 255u], lut[(v >> 16u) & 255u]); +} + +fn luma(c: vec3) -> f32 { return c.z * 0.5 + (c.x * 0.5 + c.y); } + +// easuSet returns the contributions (dirX, dirY, len) of one bilinear corner. +fn easuSet(w: f32, a: f32, b: f32, c: f32, d: f32, e: f32) -> vec3 { + var lenX = rcpLo(max(abs(d - c), abs(c - b))); + let dx = d - b; + lenX = sat(abs(dx) * lenX); + lenX = lenX * lenX; + var lenY = rcpLo(max(abs(e - c), abs(c - a))); + let dy = e - a; + lenY = sat(abs(dy) * lenY); + lenY = lenY * lenY; + return vec3(dx * w, dy * w, lenX * w + lenY * w); +} + +fn easuTap(offx: f32, offy: f32, dirx: f32, diry: f32, lx: f32, ly: f32, lob: f32, clp: f32) -> f32 { + let vx = (offx * dirx + offy * diry) * lx; + let vy = (offx * -diry + offy * dirx) * ly; + let d2 = min(vx * vx + vy * vy, clp); + var wB = 2.0 / 5.0 * d2 - 1.0; + var wA = lob * d2 - 1.0; + wB = wB * wB; + wA = wA * wA; + wB = 25.0 / 16.0 * wB - (25.0 / 16.0 - 1.0); + return wB * wA; +} + +fn lo4(a: f32, b: f32, c: f32, d: f32) -> f32 { return min(min(a, b), min(c, d)); } +fn hi4(a: f32, b: f32, c: f32, d: f32) -> f32 { return max(max(a, b), max(c, d)); } + +@compute @workgroup_size(8, 8, 1) +fn easu(@builtin(global_invocation_id) id: vec3) { + if (id.x >= p.ow || id.y >= p.oh) { return; } + let fpx = ph[2u * id.x]; + let ppx = ph[2u * id.x + 1u]; + let fpy = ph[2u * (p.ow + id.y)]; + let ppy = ph[2u * (p.ow + id.y) + 1u]; + let fx = i32(fpx); + let fy = i32(fpy); + + // b c / e f g h / i j k l / n o + let cB = load(fx, fy - 1); + let cC = load(fx + 1, fy - 1); + let cE = load(fx - 1, fy); + let cF = load(fx, fy); + let cG = load(fx + 1, fy); + let cH = load(fx + 2, fy); + let cI = load(fx - 1, fy + 1); + let cJ = load(fx, fy + 1); + let cK = load(fx + 1, fy + 1); + let cL = load(fx + 2, fy + 1); + let cN = load(fx, fy + 2); + let cO = load(fx + 1, fy + 2); + let lB = luma(cB); + let lC = luma(cC); + let lE = luma(cE); + let lF = luma(cF); + let lG = luma(cG); + let lH = luma(cH); + let lI = luma(cI); + let lJ = luma(cJ); + let lK = luma(cK); + let lL = luma(cL); + let lN = luma(cN); + let lO = luma(cO); + + let s0 = easuSet((1.0 - ppx) * (1.0 - ppy), lB, lE, lF, lG, lJ); + let s1 = easuSet(ppx * (1.0 - ppy), lC, lF, lG, lH, lK); + let s2 = easuSet((1.0 - ppx) * ppy, lF, lI, lJ, lK, lN); + let s3 = easuSet(ppx * ppy, lG, lJ, lK, lL, lO); + var dirX = s0.x + s1.x + s2.x + s3.x; + var dirY = s0.y + s1.y + s2.y + s3.y; + var ln = s0.z + s1.z + s2.z + s3.z; + + var dirR = dirX * dirX + dirY * dirY; + if (dirR < 1.0 / 32768.0) { + dirR = 1.0; + dirX = 1.0; + } else { + dirR = rsqLo(dirR); + } + dirX = dirX * dirR; + dirY = dirY * dirR; + ln = ln * 0.5; + ln = ln * ln; + let stretch = (dirX * dirX + dirY * dirY) * rcpLo(max(abs(dirX), abs(dirY))); + let lx = 1.0 + (stretch - 1.0) * ln; + let ly = 1.0 + -0.5 * ln; + let lob = 0.5 + ((1.0 / 4.0 - 0.04) - 0.5) * ln; + let clp = rcpLo(lob); + + // The reference's accumulation order: b c i j f e k l h g o n. + var a = vec3(0.0, 0.0, 0.0); + var aw = 0.0; + var w = easuTap(0.0 - ppx, -1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cB * w; aw = aw + w; + w = easuTap(1.0 - ppx, -1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cC * w; aw = aw + w; + w = easuTap(-1.0 - ppx, 1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cI * w; aw = aw + w; + w = easuTap(0.0 - ppx, 1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cJ * w; aw = aw + w; + w = easuTap(0.0 - ppx, 0.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cF * w; aw = aw + w; + w = easuTap(-1.0 - ppx, 0.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cE * w; aw = aw + w; + w = easuTap(1.0 - ppx, 1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cK * w; aw = aw + w; + w = easuTap(2.0 - ppx, 1.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cL * w; aw = aw + w; + w = easuTap(2.0 - ppx, 0.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cH * w; aw = aw + w; + w = easuTap(1.0 - ppx, 0.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cG * w; aw = aw + w; + w = easuTap(1.0 - ppx, 2.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cO * w; aw = aw + w; + w = easuTap(0.0 - ppx, 2.0 - ppy, dirX, dirY, lx, ly, lob, clp); + a = a + cN * w; aw = aw + w; + let iw = 1.0 / aw; + let rx = min(max(a.x * iw, lo4(cF.x, cG.x, cJ.x, cK.x)), hi4(cF.x, cG.x, cJ.x, cK.x)); + let ry = min(max(a.y * iw, lo4(cF.y, cG.y, cJ.y, cK.y)), hi4(cF.y, cG.y, cJ.y, cK.y)); + let rz = min(max(a.z * iw, lo4(cF.z, cG.z, cJ.z, cK.z)), hi4(cF.z, cG.z, cJ.z, cK.z)); + mid[id.y * p.ow + id.x] = vec4(rx, ry, rz, 0.0); +} + +// lobeOf is the RCAS lobe candidate of one channel; a ratio the reference +// leaves NaN (and then ignores) is no candidate. +fn lobeOf(b: f32, d: f32, e: f32, f: f32, h: f32) -> f32 { + let mn4 = lo4(b, d, f, h); + let mx4 = hi4(b, d, f, h); + let hitMin = min(mn4, e) * (1.0 / (4.0 * mx4)); + let hitMax = (1.0 - max(mx4, e)) * (1.0 / (4.0 * mn4 - 4.0)); + let cMin = select(-1.0e30, -hitMin, mx4 > 0.0); + let cMax = select(-1.0e30, hitMax, mn4 < 1.0); + return max(cMin, cMax); +} + +fn q8(v: f32) -> u32 { + if (!(v > 0.0)) { return 0u; } + return u32(min(v * 255.0 + 0.5, 255.0)); +} + +@compute @workgroup_size(8, 8, 1) +fn rcas(@builtin(global_invocation_id) id: vec3) { + if (id.x >= p.ow || id.y >= p.oh) { return; } + let x = id.x; + let y = id.y; + let xl = select(0u, x - 1u, x > 0u); + let xr = min(x + 1u, p.ow - 1u); + let yu = select(0u, y - 1u, y > 0u); + let yd = min(y + 1u, p.oh - 1u); + let e = mid[y * p.ow + x].xyz; + var o = e; + if (p.rcas != 0u) { + let b = mid[yu * p.ow + x].xyz; + let d = mid[y * p.ow + xl].xyz; + let f = mid[y * p.ow + xr].xyz; + let h = mid[yd * p.ow + x].xyz; + let lr = lobeOf(b.x, d.x, e.x, f.x, h.x); + let lg = lobeOf(b.y, d.y, e.y, f.y, h.y); + let lb = lobeOf(b.z, d.z, e.z, f.z, h.z); + let lobe = max(-(0.25 - 1.0 / 16.0), min(max(max(lr, lg), lb), 0.0)) * p.k; + let rcp = rcpMed(4.0 * lobe + 1.0); + o = (lobe * b + lobe * d + lobe * h + lobe * f + e) * rcp; + } + let i = y * p.ow + x; + if (p.mode == 0u) { + dst[i] = q8(o.x) | (q8(o.y) << 8u) | (q8(o.z) << 16u) | (255u << 24u); + } else { + dst[4u * i] = bitcast(o.x); + dst[4u * i + 1u] = bitcast(o.y); + dst[4u * i + 2u] = bitcast(o.z); + dst[4u * i + 3u] = 0u; + } +} +`