diff --git a/upscale/easu_perm_amd64.go b/upscale/easu_perm_amd64.go new file mode 100644 index 0000000..b50918c --- /dev/null +++ b/upscale/easu_perm_amd64.go @@ -0,0 +1,82 @@ +//go:build goexperiment.simd && amd64 + +package upscale + +import ( + "simd" + "simd/archsimd" +) + +// lanes is the portable vector length, 16 only with AVX-512. +func lanes() int { return simd.BroadcastFloat32s(0).Len() } + +// The gather of the EASU colour taps with AVX-512 permutes. Scaling up, the +// column table fx steps by 0 or 1 per output pixel, so the 16 outputs of a +// block read at most 16 consecutive source floats, plus 3 for the taps around +// them: two vector loads cover the window and one ConcatPermute per tap picks +// the 16 lanes, with an index vector computed once per frame and block. + +// usePerm switches e to the permute gather when it applies. +func usePerm(e *easuVec) { + if g, l := permGather(e); g != nil { + e.gather, e.lerp = g, l + } +} + +// permOK reports whether the permute gather may run here; a variable so a +// test can cover the scalar fallback. +var permOK = hasAVX512 + +func hasAVX512() bool { return archsimd.X86.AVX512() } + +func permGather(e *easuVec) (gather func(s *bandRow, o int), lerp func(s *bandRow)) { + const n = 16 + if e.n != n || lanes() != n || !permOK() { + return nil, nil + } + nb := e.owp / n + base := make([]int, nb) + idx := make([]uint32, nb*4*n) + for b := range nb { + f0 := e.fx[b*n] + base[b] = int(f0) - 1 + for l := range n { + d := e.fx[b*n+l] - f0 + if d > n-1 { // fx never decreases + return nil, nil + } + for k := range 4 { + idx[(b*4+k)*n+l] = uint32(d) + uint32(k) + } + } + } + gather = func(s *bandRow, o int) { + p := e.p + // Reslice to the capacity: newPlanes leaves vecSlack floats past each plane. + for c, src := range [nCh][]float32{p.r[:cap(p.r)], p.g[:cap(p.g)], p.b[:cap(p.b)]} { + for b, bs := range base { + w := src[o+bs:] + lo, hi := archsimd.LoadFloat32x16(w), archsimd.LoadFloat32x16(w[n:]) + for k := range 4 { + lo.ConcatPermute(hi, archsimd.LoadUint32x16(idx[(b*4+k)*n:])).Store(s.col[c][k][b*n:]) + } + } + } + } + // The analysis row holds source column x at index x+1: the window starts at + // base+2 = fx+1 (never negative), where tap k=0 is sa[f+1] and k=1 is sa[f+2]. + lerp = func(s *bandRow) { + for a, sa := range e.sa { + sa = sa[:cap(sa)] + for b, bs := range base { + w := sa[bs+2:] + lo, hi := archsimd.LoadFloat32x16(w), archsimd.LoadFloat32x16(w[n:]) + px := archsimd.LoadFloat32x16(e.ppx[b*n:]) + v0 := lo.ConcatPermute(hi, archsimd.LoadUint32x16(idx[(b*4)*n:])) + v1 := lo.ConcatPermute(hi, archsimd.LoadUint32x16(idx[(b*4+1)*n:])) + v0.Mul(archsimd.BroadcastFloat32x16(1).Sub(px)).Add(v1.Mul(px)).Store(s.an[a][b*n:]) + } + } + } + return gather, lerp +} diff --git a/upscale/easu_perm_amd64_test.go b/upscale/easu_perm_amd64_test.go new file mode 100644 index 0000000..30a4916 --- /dev/null +++ b/upscale/easu_perm_amd64_test.go @@ -0,0 +1,95 @@ +//go:build goexperiment.simd && amd64 + +package upscale + +import ( + "image" + "math/rand" + "reflect" + "simd" + "testing" +) + +// bandRowBuf returns a bandRow whose arrays have e.owp floats each. +func bandRowBuf(e *easuVec) *bandRow { + var r bandRow + buf := make([]float32, (nCh*4+3)*e.owp) + for ch := range r.col { + for d := range r.col[ch] { + r.col[ch][d], buf = buf[:e.owp:e.owp], buf[e.owp:] + } + } + for a := range r.an { + r.an[a], buf = buf[:e.owp:e.owp], buf[e.owp:] + } + return &r +} + +func TestPermGatherMatchesScalar(t *testing.T) { + if !permOK() || simd.BroadcastFloat32s(0).Len() != 16 { + t.Skip("no AVX-512") + } + rng := rand.New(rand.NewSource(3)) + for _, c := range []struct{ sw, sh, ow int }{{20, 6, 31}, {40, 6, 40}, {33, 6, 100}, {3, 3, 3}, {1, 1, 17}} { + src := image.NewNRGBA(image.Rect(0, 0, c.sw, c.sh)) + rng.Read(src.Pix) + p := fromImage(src) + e := newEasuState(p, newAxis(c.sw, c.ow), c.ow) + if reflect.ValueOf(e.gather).Pointer() == reflect.ValueOf(e.gatherScalar).Pointer() { + t.Fatalf("%v: the permute gather was not chosen", c) + } + for y := -1; y <= c.sh; y++ { + a, b := bandRowBuf(e), bandRowBuf(e) + e.gather(a, p.at(0, y)) + e.gatherScalar(b, p.at(0, y)) + e.analyse(y) + e.lerp(a) + e.lerpScalar(b) + // Only the real output columns matter; the lerp may differ in the last bit + // (the vector one is not contracted into FMA, the scalar one may be). + for ch := range a.col { + for d := range a.col[ch] { + if !reflect.DeepEqual(a.col[ch][d][:c.ow], b.col[ch][d][:c.ow]) { + t.Fatalf("%v row %d: gather differs (channel %d, tap %d)", c, y, ch, d) + } + } + } + for k := range a.an { + for ox := 0; ox < c.ow; ox++ { + if d := abs32(a.an[k][ox] - b.an[k][ox]); d > 1e-5*(1+abs32(b.an[k][ox])) { + t.Fatalf("%v row %d: lerp %d differs at %d by %g", c, y, k, ox, d) + } + } + } + } + } +} + +// The fallbacks: no AVX-512, another vector length, a table that steps by +// more than one source pixel per output pixel. +func TestPermGatherRefusals(t *testing.T) { + e := &easuVec{n: 16, owp: 16, fx: make([]int32, 16)} + for i := range e.fx { + e.fx[i] = int32(2 * i) + } + save := permOK + defer func() { permOK = save }() + permOK = func() bool { return true } + if g, _ := permGather(e); g != nil && simd.BroadcastFloat32s(0).Len() == 16 { + t.Fatal("a table stepping by 2 was accepted") + } + e.n = 8 + if g, _ := permGather(e); g != nil { + t.Fatal("8 lanes accepted") + } + e.n = 16 + permOK = func() bool { return false } + if g, _ := permGather(e); g != nil { + t.Fatal("accepted without AVX-512") + } + e.gather = nil + usePerm(e) + if e.gather != nil { + t.Fatal("usePerm switched without AVX-512") + } +} diff --git a/upscale/easu_perm_other.go b/upscale/easu_perm_other.go new file mode 100644 index 0000000..f70c339 --- /dev/null +++ b/upscale/easu_perm_other.go @@ -0,0 +1,9 @@ +//go:build goexperiment.simd && !amd64 + +package upscale + +import "simd" + +// usePerm: the permute gather exists on amd64 only (easu_perm_amd64.go); here +// the scalar gather stays. +func usePerm(*easuVec) { _ = simd.BroadcastFloat32s(0) } diff --git a/upscale/easu_simd.go b/upscale/easu_simd.go index 86f94e8..0419ed3 100644 --- a/upscale/easu_simd.go +++ b/upscale/easu_simd.go @@ -94,10 +94,15 @@ type easuVec struct { 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 + sa [3][]float32 // analysis of the source row being filled, index x+1 + offx [12][]float32 // tapDX[k] - ppx per output column (padded) + gather func(s *bandRow, o int) + lerp func(s *bandRow) } -func newEasuVec(p *planes, ax axis, ow int) easuRower { +func newEasuVec(p *planes, ax axis, ow int) easuRower { return newEasuState(p, ax, ow).row } + +func newEasuState(p *planes, ax axis, ow int) *easuVec { n := bc(0).Len() e := &easuVec{p: p, ow: ow, n: n, owp: (ow + n - 1) / n * n} e.fx, e.ppx = make([]int32, e.owp), make([]float32, e.owp) @@ -105,6 +110,12 @@ func newEasuVec(p *planes, ax axis, ow int) easuRower { 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 ox, px := range e.ppx { + e.offx[k][ox] = tapDX[k] - px + } + } buf := make([]float32, len(e.ring)*(nCh*4+3)*e.owp) for i := range e.ring { e.ring[i].y = -1 << 30 @@ -117,11 +128,14 @@ func newEasuVec(p *planes, ax axis, ow int) easuRower { e.ring[i].an[a], buf = buf[:e.owp:e.owp], buf[e.owp:] } } - sbuf := make([]float32, 3*(p.w+2+n)) + sl := p.w + 2 + n + vecSlack // analysis row, with slack for 32-float window loads + sbuf := make([]float32, 3*sl) for a := range e.sa { - e.sa[a], sbuf = sbuf[:p.w+2+n:p.w+2+n], sbuf[p.w+2+n:] + e.sa[a], sbuf = sbuf[:sl:sl], sbuf[sl:] } - return e.row + e.gather, e.lerp = e.gatherScalar, e.lerpScalar + usePerm(e) + return e } // analyse computes the EASU analysis of every source pixel of row y, for the @@ -138,11 +152,10 @@ func (e *easuVec) analyse(y int) { } } -// fill expands source row y into s. -func (e *easuVec) fill(s *bandRow, y int) { - s.y = y +// gatherScalar expands the colour taps of the source row at buffer offset o +// into s, one element at a time. +func (e *easuVec) gatherScalar(s *bandRow, o int) { p := e.p - o := p.at(0, y) for c, src := range [nCh][]float32{p.r, p.g, p.b} { c0, c1, c2, c3 := s.col[c][0], s.col[c][1], s.col[c][2], s.col[c][3] for ox, f := range e.fx { @@ -150,10 +163,22 @@ func (e *easuVec) fill(s *bandRow, y int) { c0[ox], c1[ox], c2[ox], c3[ox] = src[i-1], src[i], src[i+1], src[i+2] } } +} + +// fill expands source row y into s. +func (e *easuVec) fill(s *bandRow, y int) { + s.y = y + p := e.p + e.gather(s, p.at(0, y)) if y < -1 || y > p.h { // never the f or j row of an output pixel return } e.analyse(y) + e.lerp(s) +} + +// lerpScalar interpolates the analysis of the source row in x into s.an. +func (e *easuVec) lerpScalar(s *bandRow) { for a, sa := range e.sa { an := s.an[a] for ox, f := range e.fx { @@ -178,22 +203,30 @@ func (e *easuVec) row(fy int, py float32, dr, dg, db []float32) { e.fill(rows[k], y) } } - var offy [12]float32 - for k := range offy { - offy[k] = tapDY[k] - py + var rc rowConst + 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 x0 := 0; x0 < e.owp; x0 += e.n { - e.block(&rows, &offy, py, x0, dr, dg, db) + e.block(&rows, &rc, x0, dr, dg, db) } } +// rowConst holds the broadcasts that are the same for every vector of an +// output row, made once per row rather than once per vector. +type rowConst struct { + one, zero, ppy, ipy simd.Float32s + c04, c2516, c2516m simd.Float32s + offy [12]simd.Float32s +} + // block computes the pixels x0.. of an output row (one vector's worth). -func (e *easuVec) block(rows *bandRows, offy *[12]float32, py float32, x0 int, dr, dg, db []float32) { - one, zero := bc(1), bc(0) - ppy := bc(py) - ipy := one.Sub(ppy) +func (e *easuVec) block(rows *bandRows, rc *rowConst, x0 int, dr, dg, db []float32) { + one, zero, ppy, ipy := rc.one, rc.zero, rc.ppy, rc.ipy { - ppx := simd.LoadFloat32s(e.ppx[x0:]) // Gradient and length: the bilinear blend of the analyses of the four // source pixels f, g, j, k, already blended in x per source row. top, bot := rows[1], rows[2] @@ -217,15 +250,15 @@ func (e *easuVec) block(rows *bandRows, offy *[12]float32, py float32, x0 int, d aR, aG, aB, aW := zero, zero, zero, zero for k := range tapDX { - offx := bc(tapDX[k]).Sub(ppx) - vx := offx.Mul(dirX).Add(bc(offy[k]).Mul(dirY)).Mul(lx) - vy := offx.Mul(dirY.Neg()).Add(bc(offy[k]).Mul(dirX)).Mul(ly) + 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) d2 := vx.Mul(vx).Add(vy.Mul(vy)).Min(clp) - wB := bc(2.0 / 5.0).Mul(d2).Sub(one) + wB := rc.c04.Mul(d2).Sub(one) wA := lob.Mul(d2).Sub(one) wB = wB.Mul(wB) wA = wA.Mul(wA) - wB = bc(25.0 / 16.0).Mul(wB).Sub(bc(25.0/16.0 - 1.0)) + 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)) diff --git a/upscale/upscale.go b/upscale/upscale.go index 3606325..d28831c 100644 --- a/upscale/upscale.go +++ b/upscale/upscale.go @@ -116,10 +116,12 @@ const vecSlack = 64 func newPlanes(w, h int, alpha bool) *planes { p := &planes{w: w, h: h, stride: w + padLo + padHi} n := p.stride * (h + padLo + padHi) - // The luma plane keeps vecSlack spare floats past its end (in its capacity), - // so that a vector load starting on the last pixels stays inside the buffer. - buf := make([]float32, 4*n+vecSlack) - p.r, p.g, p.b, p.l = buf[:n:n], buf[n:2*n:2*n], buf[2*n:3*n:3*n], buf[3*n:4*n] + // Each colour plane keeps vecSlack spare floats past its end (in its + // capacity, reached by reslicing to cap), so that a vector load starting on + // the last pixels stays inside the buffer. + m := n + vecSlack + buf := make([]float32, 4*m) + p.r, p.g, p.b, p.l = buf[:n:m], buf[m:m+n:2*m], buf[2*m:2*m+n:3*m], buf[3*m:3*m+n:4*m] for k := range p.tapOff { p.tapOff[k] = int(tapDY[k])*p.stride + int(tapDX[k]) } @@ -170,13 +172,24 @@ func fromImage(src image.Image) *planes { 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: + sx = 1 + case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410: + sx = 2 + } for y := 0; y < h; y++ { o := p.at(0, y) yy := b.Min.Y + y - for x := 0; x < w; x++ { - xx := b.Min.X + x - r, g, bl := color.YCbCrToRGB(m.Y[m.YOffset(xx, yy)], m.Cb[m.COffset(xx, yy)], m.Cr[m.COffset(xx, yy)]) - p.r[o+x], p.g[o+x], p.b[o+x] = lut8[r], lut8[g], lut8[bl] + 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] } } p.finish() @@ -233,6 +246,20 @@ func fromImage(src image.Image) *planes { return p } +// ycc is color.YCbCrToRGB (same integer arithmetic), small enough to inline. +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)) +} + func fromRGBA(m *image.RGBA, w, h int, b image.Rectangle) *planes { opaque := m.Opaque() p := newPlanes(w, h, !opaque) diff --git a/upscale/ycc_test.go b/upscale/ycc_test.go new file mode 100644 index 0000000..1320a91 --- /dev/null +++ b/upscale/ycc_test.go @@ -0,0 +1,53 @@ +package upscale + +import ( + "image" + "image/color" + "testing" +) + +// TestYccIsStdlib checks the inlined conversion against color.YCbCrToRGB on +// every input. +func TestYccIsStdlib(t *testing.T) { + for y := 0; y < 256; y++ { + for cb := 0; cb < 256; cb++ { + for cr := 0; cr < 256; cr++ { + 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) + } + } + } + } +} + +// TestFromYCbCrAllRatios compares the planar conversion of every subsampling +// ratio, on a sub-image with an odd origin, with the colour model's At(). +func TestFromYCbCrAllRatios(t *testing.T) { + for _, ratio := range []image.YCbCrSubsampleRatio{ + image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420, + image.YCbCrSubsampleRatio440, image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410, + } { + full := image.NewYCbCr(image.Rect(0, 0, 23, 19), ratio) + for i := range full.Y { + full.Y[i] = uint8(i * 7) + } + for i := range full.Cb { + full.Cb[i], full.Cr[i] = uint8(i*13), uint8(255-i*5) + } + for _, src := range []*image.YCbCr{full, full.SubImage(image.Rect(3, 5, 18, 14)).(*image.YCbCr)} { + p := fromImage(src) + b := src.Bounds() + for y := 0; y < b.Dy(); y++ { + for x := 0; x < b.Dx(); x++ { + c := color.RGBAModel.Convert(src.At(b.Min.X+x, b.Min.Y+y)).(color.RGBA) + i := p.at(x, y) + if p.r[i] != lut8[c.R] || p.g[i] != lut8[c.G] || p.b[i] != lut8[c.B] { + t.Fatalf("ratio %v (%d,%d): planar %v,%v,%v, At %v", ratio, x, y, p.r[i], p.g[i], p.b[i], c) + } + } + } + } + } +}