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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,15 @@ jobs:
- run: go version && go env GOARCH GOEXPERIMENT
- run: go vet ./...
- run: go test ./...
# The vector EASU/RCAS kernels (upscale/easu_simd.go) exist only under the
# experiment, so the 100% gate of the scalar lanes never sees them.
- name: upscale coverage gate, vector lane
run: |
go test -coverprofile=cover-simd.out ./upscale
cov=$(go tool cover -func=cover-simd.out | tail -1 | awk '{print $3}' | tr -d '%')
echo "coverage: ${cov}%"
awk -v t="$cov" 'BEGIN { exit !(t+0 >= 100.0) }' || {
echo "::error::upscale coverage ${cov}% < 100% under GOEXPERIMENT=simd"; exit 1; }

# The one 32-bit target. 386 runs natively on the amd64 runner, without qemu,
# and it is where int and uint are 32 bits wide: a length converted to int
Expand Down
275 changes: 207 additions & 68 deletions upscale/easu_simd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,35 @@

package upscale

import "simd"
import (
"simd"
"unsafe"
)

// Vector EASU (GOEXPERIMENT=simd, Go 1.27): the portable simd package maps to
// AVX2 on amd64 and NEON on arm64. The 12 taps of each output pixel are
// gathered by scalar loads into [12][maxLanes] stack arrays (there is no
// 2D gather in hardware worth using here), then the direction, length and
// weight arithmetic runs one pixel per lane. Every expression is the scalar
// one of easuPixel, evaluated in the same order, so results differ from it
// only by the compiler's FMA contraction.
// AVX2 on amd64 and NEON on arm64. The vector lanes run along an output row.
//
// The 12 taps of an output pixel sit at fixed offsets around the integer
// position of its "f" tap, and that position (the column phase table, ax)
// is the same for every output row. So the gather is done once per SOURCE
// row, not once per output pixel: for each source row and each column offset
// dx in -1..2 an array holds src[fx[ox]+dx] for every output column ox,
// and the taps of a whole vector of pixels are then plain contiguous loads.
// Consecutive output rows share most of their four source rows, so a ring of
// four rows serves them all.
//
// Every expression is the scalar one of easuPixel, evaluated in the same
// order, so results differ from it only by the compiler's FMA contraction.

const maxLanes = 16

// useVec reports whether easuRowVec can run here: the hardware vector must
// fit the stack buffers.
func useVec() bool { return bc(0).Len() <= maxLanes }
// useVec reports whether the vector kernels are worth using here.
func useVec() bool { return bc(0).Len() >= 4 }

func init() {
if useVec() {
easuRowFn, rcasRowFn = easuRowVec, rcasRowVec
newEasuFn, rcasRowFn, packOpaqueFn = newEasuVec, rcasRowVec, packOpaqueVec
}
}

type tapBuf [12][maxLanes]float32

func ld(a *[maxLanes]float32) simd.Float32s { return simd.LoadFloat32s(a[:]) }

func bc(v float32) simd.Float32s { return simd.BroadcastFloat32s(v) }

func vRcpLo(a simd.Float32s) simd.Float32s {
Expand All @@ -40,53 +43,163 @@ func vRsqLo(a simd.Float32s) simd.Float32s {

func vSat(a simd.Float32s) simd.Float32s { return a.Max(bc(0)).Min(bc(1)) }

// vEasuSet is easuSet, one pixel per lane.
func vEasuSet(dirX, dirY, ln, w, a, b, c, d, e simd.Float32s) (simd.Float32s, simd.Float32s, simd.Float32s) {
// vEasuSet is the per-corner part of easuSet, one pixel per lane: the
// gradient (dx, dy) and the length term lenX^2 + lenY^2 of the five luma
// taps of a "+" shape
//
// a
// b c d
// e
//
// They depend on the source pixel alone, not on the output pixel, so they
// are computed once per source pixel and then interpolated (the weights of
// FsrEasuSetF are bilinear in the fractional position).
func vEasuSet(a, b, c, d, e simd.Float32s) (dx, dy, ln simd.Float32s) {
lenX := vRcpLo(d.Sub(c).Abs().Max(c.Sub(b).Abs()))
dx := d.Sub(b)
dirX = dirX.Add(dx.Mul(w))
dx = d.Sub(b)
lenX = vSat(dx.Abs().Mul(lenX))
lenX = lenX.Mul(lenX)
ln = ln.Add(lenX.Mul(w))
lenY := vRcpLo(e.Sub(c).Abs().Max(c.Sub(a).Abs()))
dy := e.Sub(a)
dirY = dirY.Add(dy.Mul(w))
dy = e.Sub(a)
lenY = vSat(dy.Abs().Mul(lenY))
lenY = lenY.Mul(lenY)
ln = ln.Add(lenY.Mul(w))
return dirX, dirY, ln
return dx, dy, lenX.Add(lenY)
}

// Channels of a band row.
const (
chR = iota
chG
chB
nCh
)

// bandRow is one source row expanded to output columns: col[ch][dx+1][ox] is
// the value at source column fx[ox]+dx, for dx -1..2, and an[0..2][ox] the
// gradient dx, dy and length term interpolated in x at the pixel's position.
type bandRow struct {
y int
col [nCh][4][]float32
an [3][]float32
}

// easuRowVec computes one output row of EASU: the pixels 0..ow-1, whose "f"
// taps are at source row fy, fractional row position py.
func easuRowVec(p *planes, ax axis, fy int, py float32, ow int, dr, dg, db []float32) {
var tl, tr, tg, tb tapBuf
var ppxs, out [maxLanes]float32
// bandRows are the four source rows fy-1..fy+2 of an output row.
type bandRows [4]*bandRow

// easuVec is the per-frame state of the vector EASU.
type easuVec struct {
p *planes
ow, owp int // output width, and it rounded up to whole vectors
n int // vector length
fx []int32 // integer position of the "f" tap per output column (padded)
ppx []float32 // fractional position per output column (padded)
ring [4]bandRow
sa [3][]float32 // analysis of the source row being filled, index x+1
}

func newEasuVec(p *planes, ax axis, ow int) easuRower {
n := bc(0).Len()
one, zero := bc(1), bc(0)
ppy := bc(py)
for x0 := 0; x0 < ow; x0 += n {
cnt := min(n, ow-x0)
for j := 0; j < n; j++ {
ox := x0 + min(j, cnt-1) // spare lanes repeat the last pixel
base := p.at(int(ax.fp[ox]), fy)
ppxs[j] = ax.pp[ox]
for k, off := range p.tapOff {
i := base + off
tl[k][j], tr[k][j], tg[k][j], tb[k][j] = p.l[i], p.r[i], p.g[i], p.b[i]
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)
for ox := range e.fx {
j := min(ox, ow-1) // spare lanes repeat the last pixel
e.fx[ox], e.ppx[ox] = ax.fp[j], ax.pp[j]
}
buf := make([]float32, len(e.ring)*(nCh*4+3)*e.owp)
for i := range e.ring {
e.ring[i].y = -1 << 30
for c := range e.ring[i].col {
for d := range e.ring[i].col[c] {
e.ring[i].col[c][d], buf = buf[:e.owp:e.owp], buf[e.owp:]
}
}
ppx := ld(&ppxs)
// Luma taps by the reference's names.
bL, cL, iL, jL, fL, eL := ld(&tl[0]), ld(&tl[1]), ld(&tl[2]), ld(&tl[3]), ld(&tl[4]), ld(&tl[5])
kL, lL, hL, gL, oL, nL := ld(&tl[6]), ld(&tl[7]), ld(&tl[8]), ld(&tl[9]), ld(&tl[10]), ld(&tl[11])

ipx, ipy := one.Sub(ppx), one.Sub(ppy)
dirX, dirY, ln := zero, zero, zero
dirX, dirY, ln = vEasuSet(dirX, dirY, ln, ipx.Mul(ipy), bL, eL, fL, gL, jL)
dirX, dirY, ln = vEasuSet(dirX, dirY, ln, ppx.Mul(ipy), cL, fL, gL, hL, kL)
dirX, dirY, ln = vEasuSet(dirX, dirY, ln, ipx.Mul(ppy), fL, iL, jL, kL, nL)
dirX, dirY, ln = vEasuSet(dirX, dirY, ln, ppx.Mul(ppy), gL, jL, kL, lL, oL)
for a := range e.ring[i].an {
e.ring[i].an[a], buf = buf[:e.owp:e.owp], buf[e.owp:]
}
}
sbuf := make([]float32, 3*(p.w+2+n))
for a := range e.sa {
e.sa[a], sbuf = sbuf[:p.w+2+n:p.w+2+n], sbuf[p.w+2+n:]
}
return e.row
}

// analyse computes the EASU analysis of every source pixel of row y, for the
// columns -1..w (the corners a bilinear footprint can touch).
func (e *easuVec) analyse(y int) {
p := e.p
l := p.l[:len(p.l)+vecSlack] // the slack newPlanes left past the plane
ld := func(x, dy int) simd.Float32s { return simd.LoadFloat32s(l[p.at(x, y+dy):]) }
for x := -1; x < p.w+1; x += e.n {
dx, dy, ln := vEasuSet(ld(x, -1), ld(x-1, 0), ld(x, 0), ld(x+1, 0), ld(x, 1))
dx.Store(e.sa[0][x+1:])
dy.Store(e.sa[1][x+1:])
ln.Store(e.sa[2][x+1:])
}
}

// fill expands source row y into s.
func (e *easuVec) fill(s *bandRow, y int) {
s.y = y
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 {
i := o + int(f)
c0[ox], c1[ox], c2[ox], c3[ox] = src[i-1], src[i], src[i+1], src[i+2]
}
}
if y < -1 || y > p.h { // never the f or j row of an output pixel
return
}
e.analyse(y)
for a, sa := range e.sa {
an := s.an[a]
for ox, f := range e.fx {
px := e.ppx[ox]
an[ox] = sa[f+1]*(1-px) + sa[f+2]*px
}
}
}

// tap returns tap k of channel c for the pixels starting at output x0.
func (rows *bandRows) tap(c, k, x0 int) simd.Float32s {
return simd.LoadFloat32s(rows[int(tapDY[k])+1].col[c][int(tapDX[k])+1][x0:])
}

// row is the easuRower of the vector kernel.
func (e *easuVec) row(fy int, py float32, dr, dg, db []float32) {
var rows bandRows // source rows fy-1..fy+2
for k := range rows {
y := fy - 1 + k
rows[k] = &e.ring[(y+4)&3]
if rows[k].y != y {
e.fill(rows[k], y)
}
}
var offy [12]float32
for k := range offy {
offy[k] = tapDY[k] - py
}
for x0 := 0; x0 < e.owp; x0 += e.n {
e.block(&rows, &offy, py, x0, dr, dg, db)
}
}

// 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)
{
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]
dirX := ipy.Mul(simd.LoadFloat32s(top.an[0][x0:])).Add(ppy.Mul(simd.LoadFloat32s(bot.an[0][x0:])))
dirY := ipy.Mul(simd.LoadFloat32s(top.an[1][x0:])).Add(ppy.Mul(simd.LoadFloat32s(bot.an[1][x0:])))
ln := ipy.Mul(simd.LoadFloat32s(top.an[2][x0:])).Add(ppy.Mul(simd.LoadFloat32s(bot.an[2][x0:])))

dirR := dirX.Mul(dirX).Add(dirY.Mul(dirY))
small := dirR.Less(bc(1.0 / 32768.0))
Expand All @@ -104,35 +217,61 @@ func easuRowVec(p *planes, ax axis, fy int, py float32, ow int, dr, dg, db []flo

aR, aG, aB, aW := zero, zero, zero, zero
for k := range tapDX {
offx, offy := bc(tapDX[k]).Sub(ppx), bc(tapDY[k]).Sub(ppy)
vx := offx.Mul(dirX).Add(offy.Mul(dirY)).Mul(lx)
vy := offx.Mul(dirY.Neg()).Add(offy.Mul(dirX)).Mul(ly)
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)
d2 := vx.Mul(vx).Add(vy.Mul(vy)).Min(clp)
wB := bc(2.0 / 5.0).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))
w := wB.Mul(wA)
aR = aR.Add(ld(&tr[k]).Mul(w))
aG = aG.Add(ld(&tg[k]).Mul(w))
aB = aB.Add(ld(&tb[k]).Mul(w))
aR = aR.Add(rows.tap(chR, k, x0).Mul(w))
aG = aG.Add(rows.tap(chG, k, x0).Mul(w))
aB = aB.Add(rows.tap(chB, k, x0).Mul(w))
aW = aW.Add(w)
}
rcp := one.Div(aW)
vFinish(aR, rcp, &tr, &out, dr[x0:x0+cnt])
vFinish(aG, rcp, &tg, &out, dg[x0:x0+cnt])
vFinish(aB, rcp, &tb, &out, db[x0:x0+cnt])
vFinish(aR, rcp, rows.tap(chR, 4, x0), rows.tap(chR, 9, x0), rows.tap(chR, 3, x0), rows.tap(chR, 6, x0), dr[x0:])
vFinish(aG, rcp, rows.tap(chG, 4, x0), rows.tap(chG, 9, x0), rows.tap(chG, 3, x0), rows.tap(chG, 6, x0), dg[x0:])
vFinish(aB, rcp, rows.tap(chB, 4, x0), rows.tap(chB, 9, x0), rows.tap(chB, 3, x0), rows.tap(chB, 6, x0), db[x0:])
}
}

// vFinish normalises one channel and dering-clamps it to the range of the
// four nearest pixels f, g, j, k (taps 4, 9, 3, 6).
func vFinish(a, rcp simd.Float32s, t *tapBuf, out *[maxLanes]float32, dst []float32) {
f, g, j, k := ld(&t[4]), ld(&t[9]), ld(&t[3]), ld(&t[6])
// vFinish normalises one channel, dering-clamps it to the range of the four
// nearest pixels f, g, j, k and stores the pixels that fit in dst.
func vFinish(a, rcp, f, g, j, k simd.Float32s, dst []float32) {
lo, hi := f.Min(g).Min(j.Min(k)), f.Max(g).Max(j.Max(k))
a.Mul(rcp).Max(lo).Min(hi).Store(out[:])
copy(dst, out[:])
v := a.Mul(rcp).Max(lo).Min(hi)
if len(dst) >= v.Len() {
v.Store(dst)
} else {
v.StorePart(dst)
}
}

// vQ8 is q8, one value per lane, as int32 0..255: NaN and values at or
// below 0 give 0.
func vQ8(v simd.Float32s) simd.Int32s {
t := v.Mul(bc(255)).Add(bc(0.5)).Masked(v.Greater(bc(0)))
return t.Min(bc(255)).ConvertToInt32()
}

// packOpaqueVec is packOpaque with each vector of pixels packed into
// little-endian 0xAABBGGRR words, which is the RGBA byte order.
func packOpaqueVec(d []byte, r, g, b []float32) {
n := bc(0).Len()
x := 0
if len(r) >= n {
words := unsafe.Slice((*int32)(unsafe.Pointer(&d[0])), len(r))
a := simd.BroadcastInt32s(-1 << 24) // 0xFF000000
for ; x+n <= len(r); x += n {
w := vQ8(simd.LoadFloat32s(r[x:])).Or(vQ8(simd.LoadFloat32s(g[x:])).ShiftAllLeft(8))
w.Or(vQ8(simd.LoadFloat32s(b[x:])).ShiftAllLeft(16)).Or(a).Store(words[x:])
}
}
packOpaque(d[4*x:], r[x:], g[x:], b[x:])
}

// vnmax is nmax, one pixel per lane: a NaN operand yields the other one.
Expand Down
Loading
Loading