From c927cbd6e198ea052cf8924d4be6f47b718a7c8c Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 11:26:13 +0100 Subject: [PATCH] pixel: horizontal 8-tap convolution with VPMADDUBSW Take filterHorizMadd and filterHorizMadd8 from govpx 43f826d8 (BSD-3, attributed in the file header) for the step == 1 case of filterWide8 and filterNarrow8. Tap pairs multiply byte pairs with DotProductPairsSaturated, the instruction libvpx's vpx_filter_block1d*_h8 kernels use. maddPairs proves per tap set that no partial sum saturates except the last add, so the result is exactly clamp((sum+64)>>7, 0, 255); other tap sets fall back to the existing kernels. Add TestMaddKernelsAgainstScalar (regular, sharp, smooth, bilinear and 200 random tap sets, extremal inputs, sources cut exactly at the footprint), BenchmarkDecodeClip, and docs/perf/speed-log.md. crowd_run 1080p, fractal, one core, 6 interleaved rounds, median us/frame: VP9 1 tile 7210 -> 6944, VP9 4 tiles 7581 -> 7304, VP8 4969 -> 4961. Co-Authored-By: Claude Sonnet 5.5 --- bench_test.go | 62 ++++++++++ docs/perf/speed-log.md | 29 +++++ internal/pixel/filter_arm64.go | 5 + internal/pixel/filter_avx2.go | 3 + internal/pixel/filter_madd_avx2.go | 192 +++++++++++++++++++++++++++++ internal/pixel/filter_madd_test.go | 102 +++++++++++++++ internal/pixel/filter_six_simd.go | 3 + 7 files changed, 396 insertions(+) create mode 100644 bench_test.go create mode 100644 docs/perf/speed-log.md create mode 100644 internal/pixel/filter_madd_avx2.go create mode 100644 internal/pixel/filter_madd_test.go diff --git a/bench_test.go b/bench_test.go new file mode 100644 index 0000000..8f72734 --- /dev/null +++ b/bench_test.go @@ -0,0 +1,62 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package vpx_test + +import ( + "os" + "testing" + + "github.com/go-avkit/vpx/vp8" + "github.com/go-avkit/vpx/vp9" +) + +// benchClip decodes the IVF clip named by VPX_BENCH_FILE (VP8 or VP9, told by the IVF fourcc) on +// one thread and reports the decode time per frame. The test binary is run by the speed study's +// interleaving runner; without the variable the benchmark is skipped. +func benchClip(b *testing.B) { + path := os.Getenv("VPX_BENCH_FILES") + if path == "" { + b.Skip("VPX_BENCH_FILES is not set") + } + data, err := os.ReadFile(path) + if err != nil { + b.Fatal(err) + } + samples, err := ivfSamples(data) + if err != nil { + b.Fatal(err) + } + isVP8 := string(data[8:12]) == "VP80" + b.ResetTimer() + for range b.N { + if isVP8 { + d, err := vp8.New(vp8.Options{}) + if err != nil { + b.Fatal(err) + } + for i, s := range samples { + if err := d.DecodeWithPTS(s, uint64(i)); err != nil { + b.Fatal(err) + } + d.NextFrame() + } + d.Close() + } else { + d, err := vp9.New(vp9.Options{}) + if err != nil { + b.Fatal(err) + } + for i, s := range samples { + if err := d.DecodeWithPTS(s, uint64(i)); err != nil { + b.Fatal(err) + } + d.NextFrame() + } + d.Close() + } + } + b.ReportMetric(float64(b.Elapsed().Nanoseconds())/float64(b.N*len(samples)), "ns/frame") +} + +func BenchmarkDecodeClip(b *testing.B) { benchClip(b) } diff --git a/docs/perf/speed-log.md b/docs/perf/speed-log.md new file mode 100644 index 0000000..4da62da --- /dev/null +++ b/docs/perf/speed-log.md @@ -0,0 +1,29 @@ +# Speed log + +Timings: `fractal` (Ryzen 9 7950X), linux/amd64, `GOEXPERIMENT=simd`, one pinned core, load under 3, +interleaved rounds (6) against the previous tag, `BenchmarkDecodeClip` (`bench_test.go`) on the +crowd_run 1080p 300-frame clips, median µs per frame. + +| change | VP9 1 tile | VP9 4 tiles | VP8 | +|---|---|---|---| +| v0.1.0 (M0) | 7210 | 7581 | 4969 | +| horizontal 8-tap with VPMADDUBSW (from govpx 43f826d8) | 6944 (1.038x) | 7304 (1.038x) | 4961 (1.002x) | + +libvpx single core, same clips (M0 protocol): 2623, 2610, 2427. + +## Tried and not kept + +- VP8 six-tap horizontal through the same kernel (taps padded with two zeros): 5131 against + 5295 µs, slower than the existing six-tap kernels, reverted. +- Vertical 8-tap with VPMADDUBSW: needs a byte interleave of two source rows. `simd/archsimd` on + amd64 (Go 1.27.4) has no byte `InterleaveLo`/`InterleaveHi`, so the interleave costs three + operations (two shuffles and an or) per half and the kernel does not beat the widening one by + construction; it needs either an assembly kernel or a byte unpack in archsimd. + +## Not done + +- F1 (zero-copy hand-out): in this module the decoders already return a view of their frame buffer + (`Image`), and the copy of `copyVP9ImageToPublic` runs only with `ByteAlignment` or + post-processing. The copy the design means is made by go-avkit/decode, and the copy/alloc stage + is 1.7 % (VP9) and 3.1 % (VP8) of the M0 profile, so F1 is worth at most that. +- Loop filter (K1) and the move of the convolution into `go-videodsp/kernels`. diff --git a/internal/pixel/filter_arm64.go b/internal/pixel/filter_arm64.go index a00d907..da953dd 100644 --- a/internal/pixel/filter_arm64.go +++ b/internal/pixel/filter_arm64.go @@ -17,6 +17,11 @@ import ( "simd/archsimd" ) +// filterHorizMadd8 is the amd64 VPMADDUBSW kernel; arm64 has no counterpart. +func filterHorizMadd8(src []byte, ss int, dst []byte, ds, w, h int, taps []int16) bool { + return false +} + // filterWide8 implements ARM64 NEON 8-tap and 2-tap subpixel convolution using // unsigned widening multiplies (UMULL / MulWidenLo) and URHADD (Average). // diff --git a/internal/pixel/filter_avx2.go b/internal/pixel/filter_avx2.go index 96d9c27..0b7da66 100644 --- a/internal/pixel/filter_avx2.go +++ b/internal/pixel/filter_avx2.go @@ -25,6 +25,9 @@ func filterWide8(src []byte, ss int, dst []byte, ds, w, h, step int, taps []int1 if len(taps) != 8 || w <= 0 || w%16 != 0 || h <= 0 || ss < 0 || ds < 0 || step < 0 { return false } + if step == 1 && filterHorizMadd(src, ss, dst, ds, w, h, taps) { + return true + } mode := narrow8Mode(taps) if mode == 0 { return false diff --git a/internal/pixel/filter_madd_avx2.go b/internal/pixel/filter_madd_avx2.go new file mode 100644 index 0000000..5e8a011 --- /dev/null +++ b/internal/pixel/filter_madd_avx2.go @@ -0,0 +1,192 @@ +// Copyright (c) 2026, The govpx authors. All rights reserved. +// Use of this source code is governed by a BSD-3-Clause licence, in +// third_party/govpx/LICENSE. +// +// Taken from github.com/thesyncim/govpx, commit 43f826d878b242766d66ef0a18a99aeeab1c3134 +// (internal/pixel/filter_madd_avx2.go). Where it cites a libvpx source file, that file is +// libvpx's, under the licence and patent grant in third_party/libvpx/. + +//go:build goexperiment.simd && amd64 && !purego + +package pixel + +import ( + "encoding/binary" + "simd/archsimd" +) + +// Horizontal 8-tap convolution with VPMADDUBSW, the instruction libvpx's +// vpx_filter_block1d*_h8 kernels are built around (vpx_dsp/x86/ +// vpx_subpixel_8t_intrin_avx2.c, vpx_subpixel_8t_intrin_ssse3.c, whose +// convolve8_8_ssse3 in convolve_ssse3.h adds x0+x2 and x1+x3, folds the 64 +// rounding constant in early and saturates only on the last add; this kernel +// proves the same exactness per tap set instead of assuming it). +// +// A load at p+2m holds, in 16-bit lane j, the byte pair (p[2m+2j], p[2m+2j+1]). +// Multiplying that pair by the tap pair (t[2m], t[2m+1]) and adding the two +// products gives, for output x = 2j, the part of its sum that taps 2m and 2m+1 +// contribute. Four loads at p, p+2, p+4, p+6 therefore give the even outputs, +// four loads at p+1, p+3, p+5, p+7 the odd ones, with no widening and no +// byte shuffles. The two results are rounded, shifted and clamped to bytes in +// their 16-bit lanes, then merged as even | odd<<8, which is already the +// interleaved byte order of the output row. + +// maddPairs returns the four tap pairs packed little endian for VPMADDUBSW and +// whether the kernel is exact for these taps. +// +// Exactness: each pair sum must fit in int16 without saturating, and the +// accumulation order (outer pair 0 + pair 3, then the smaller of pairs 1 and +// 2, then the rounding constant, then the larger) must keep every partial sum +// but the last inside int16. The last add may saturate at the top: a true sum +// of 32768 or more rounds to a value above 255 and clamps to 255, as does the +// saturated 32767. Saturation at the bottom is excluded by the same interval +// check, so the result always equals clamp((sum+64)>>7, 0, 255). +func maddPairs(taps []int16) (pairs [4]uint16, ok bool) { + if len(taps) != 8 { + return pairs, false + } + var lo, hi [4]int + for m := range 4 { + a, b := int(taps[2*m]), int(taps[2*m+1]) + if a < -128 || a > 127 || b < -128 || b > 127 { + return pairs, false + } + pairs[m] = uint16(uint8(int8(a))) | uint16(uint8(int8(b)))<<8 + lo[m] = 255 * (min(a, 0) + min(b, 0)) + hi[m] = 255 * (max(a, 0) + max(b, 0)) + if lo[m] < -32768 || hi[m] > 32767 { + return pairs, false + } + } + s1lo, s1hi := lo[0]+lo[3], hi[0]+hi[3] + if s1lo < -32768 || s1hi > 32767 { + return pairs, false + } + s2lo, s2hi := s1lo+min(lo[1], lo[2])+64, s1hi+min(hi[1], hi[2])+64 + if s2lo < -32768 || s2hi > 32767 { + return pairs, false + } + if s2lo+max(lo[1], lo[2]) < -32768 { + return pairs, false + } + return pairs, true +} + +// filterHorizMadd runs the horizontal pass for step == 1 and w%16 == 0. +func filterHorizMadd(src []byte, ss int, dst []byte, ds, w, h int, taps []int16) bool { + if w <= 0 || w%16 != 0 || h <= 0 || ss < 0 || ds < 0 { + return false + } + pairs, ok := maddPairs(taps) + if !ok { + return false + } + _ = src[(h-1)*ss+w-1+7] + _ = dst[(h-1)*ds+w-1] + defer archsimd.ClearAVXUpperBits() + + var c [4]archsimd.Int8x16 + var c2 [4]archsimd.Int8x32 + for m := range 4 { + c[m] = archsimd.BroadcastUint16x8(pairs[m]).ReshapeToUint8s().BitsToInt8() + c2[m] = archsimd.BroadcastUint16x16(pairs[m]).ReshapeToUint8s().BitsToInt8() + } + bias := archsimd.BroadcastInt16x8(64) + zero := archsimd.LoadInt16x8Array(&packZero16) + max255 := archsimd.BroadcastInt16x8(255) + bias2 := archsimd.BroadcastInt16x16(64) + zero2 := archsimd.LoadInt16x16Array(&packZero16x16) + max2552 := archsimd.BroadcastInt16x16(255) + + for y := range h { + in := src[y*ss:] + out := dst[y*ds:] + x := 0 + for ; x+32 <= w; x += 32 { + p := in[x:] + e0 := archsimd.LoadUint8x32(p).DotProductPairsSaturated(c2[0]) + e1 := archsimd.LoadUint8x32(p[2:]).DotProductPairsSaturated(c2[1]) + e2 := archsimd.LoadUint8x32(p[4:]).DotProductPairsSaturated(c2[2]) + e3 := archsimd.LoadUint8x32(p[6:]).DotProductPairsSaturated(c2[3]) + o0 := archsimd.LoadUint8x32(p[1:]).DotProductPairsSaturated(c2[0]) + o1 := archsimd.LoadUint8x32(p[3:]).DotProductPairsSaturated(c2[1]) + o2 := archsimd.LoadUint8x32(p[5:]).DotProductPairsSaturated(c2[2]) + o3 := archsimd.LoadUint8x32(p[7:]).DotProductPairsSaturated(c2[3]) + e := e0.AddSaturated(e3).AddSaturated(e1.Min(e2)).AddSaturated(bias2).AddSaturated(e1.Max(e2)) + o := o0.AddSaturated(o3).AddSaturated(o1.Min(o2)).AddSaturated(bias2).AddSaturated(o1.Max(o2)) + e = e.ShiftAllRight(7).Max(zero2).Min(max2552) + o = o.ShiftAllRight(7).Max(zero2).Min(max2552) + e.Or(o.ShiftAllLeft(8)).ToBits().ReshapeToUint8s().Store(out[x:]) + } + for ; x+16 <= w; x += 16 { + p := in[x:] + e0 := archsimd.LoadUint8x16(p).DotProductPairsSaturated(c[0]) + e1 := archsimd.LoadUint8x16(p[2:]).DotProductPairsSaturated(c[1]) + e2 := archsimd.LoadUint8x16(p[4:]).DotProductPairsSaturated(c[2]) + e3 := archsimd.LoadUint8x16(p[6:]).DotProductPairsSaturated(c[3]) + o0 := archsimd.LoadUint8x16(p[1:]).DotProductPairsSaturated(c[0]) + o1 := archsimd.LoadUint8x16(p[3:]).DotProductPairsSaturated(c[1]) + o2 := archsimd.LoadUint8x16(p[5:]).DotProductPairsSaturated(c[2]) + o3 := archsimd.LoadUint8x16(p[7:]).DotProductPairsSaturated(c[3]) + e := e0.AddSaturated(e3).AddSaturated(e1.Min(e2)).AddSaturated(bias).AddSaturated(e1.Max(e2)) + o := o0.AddSaturated(o3).AddSaturated(o1.Min(o2)).AddSaturated(bias).AddSaturated(o1.Max(o2)) + e = e.ShiftAllRight(7).Max(zero).Min(max255) + o = o.ShiftAllRight(7).Max(zero).Min(max255) + e.Or(o.ShiftAllLeft(8)).ToBits().ReshapeToUint8s().Store(out[x:]) + } + } + return true +} + +var packZero16x16 [16]int16 + +// madd8Shuffles[m] gathers, for the eight outputs of one 16-byte load, the byte +// pairs (p[j+2m], p[j+2m+1]) that tap pair m multiplies: word j of the result +// belongs to output j. +var madd8Shuffles = [4][16]int8{ + {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8}, + {2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10}, + {4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12}, + {6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14}, +} + +// filterHorizMadd8 runs the horizontal pass for step == 1 and w == 4 or w%8 == 0, +// eight outputs per 16-byte load. +func filterHorizMadd8(src []byte, ss int, dst []byte, ds, w, h int, taps []int16) bool { + if w <= 0 || (w != 4 && w%8 != 0) || h <= 0 || ss < 0 || ds < 0 { + return false + } + pairs, ok := maddPairs(taps) + if !ok { + return false + } + if len(src) < (h-1)*ss+max(w-8, 0)+16 || len(dst) < (h-1)*ds+w { + return false + } + defer archsimd.ClearAVXUpperBits() + var c, idx [4]archsimd.Int8x16 + for m := range 4 { + c[m] = archsimd.BroadcastUint16x8(pairs[m]).ReshapeToUint8s().BitsToInt8() + idx[m] = archsimd.LoadInt8x16Array(&madd8Shuffles[m]) + } + bias := archsimd.BroadcastInt16x8(64) + for y := range h { + in := src[y*ss:] + out := dst[y*ds:] + for x := 0; x < w; x += 8 { + v := archsimd.LoadUint8x16(in[x:]) + x0 := v.PermuteOrZero(idx[0]).DotProductPairsSaturated(c[0]) + x1 := v.PermuteOrZero(idx[1]).DotProductPairsSaturated(c[1]) + x2 := v.PermuteOrZero(idx[2]).DotProductPairsSaturated(c[2]) + x3 := v.PermuteOrZero(idx[3]).DotProductPairsSaturated(c[3]) + s := x0.AddSaturated(x3).AddSaturated(x1.Min(x2)).AddSaturated(bias).AddSaturated(x1.Max(x2)) + b := packBytes(s.ShiftAllRight(7)) + if w == 4 { + binary.LittleEndian.PutUint32(out, b.ReshapeToUint32s().GetElem(0)) + } else { + storeBytes8(out[x:], b) + } + } + } + return true +} diff --git a/internal/pixel/filter_madd_test.go b/internal/pixel/filter_madd_test.go new file mode 100644 index 0000000..f98fc27 --- /dev/null +++ b/internal/pixel/filter_madd_test.go @@ -0,0 +1,102 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +//go:build goexperiment.simd && amd64 && !purego + +package pixel + +import ( + "bytes" + "math/rand/v2" + "testing" +) + +// vp9Taps are the libvpx 8-tap kernels of the regular, sharp and smooth families and the 4-tap +// and bilinear rows the decoders also feed to these kernels. +var vp9Taps = [][]int16{ + {0, 1, -5, 126, 8, -3, 1, 0}, {-1, 3, -10, 122, 18, -6, 2, 0}, {-1, 4, -13, 118, 27, -9, 3, -1}, + {-1, 4, -16, 112, 37, -11, 4, -1}, {-1, 5, -18, 105, 48, -14, 4, -1}, {-1, 5, -19, 97, 58, -16, 5, -1}, + {-1, 6, -19, 88, 68, -18, 5, -1}, {-1, 6, -19, 78, 78, -19, 6, -1}, + {-3, -1, 32, 64, 38, 1, -3, 0}, {-2, -2, 29, 63, 41, 2, -3, 0}, {-2, -2, 26, 63, 43, 4, -4, 0}, + {-1, -3, 24, 62, 46, 5, -4, -1}, {-1, -3, 21, 60, 49, 7, -4, -1}, {-1, -4, 18, 59, 51, 9, -4, 0}, + {-1, -4, 16, 57, 53, 12, -4, -1}, {-1, -4, 14, 55, 55, 14, -4, -1}, + {-3, 7, -17, 119, 28, -11, 5, -1}, {-4, 11, -23, 111, 47, -17, 8, -3}, {-4, 12, -26, 100, 66, -22, 11, -3}, + {0, 0, 0, 64, 64, 0, 0, 0}, {0, 0, 0, 120, 8, 0, 0, 0}, {0, 0, -6, 126, 8, -2, 0, 0}, +} + +func randTaps(r *rand.Rand) []int16 { + for { + t := make([]int16, 8) + sum := 0 + for i := range t { + t[i] = int16(r.IntN(61) - 20) + sum += int(t[i]) + } + t[3] += int16(128 - sum) + return t + } +} + +// TestMaddKernelsAgainstScalar checks the VPMADDUBSW kernels, horizontal and vertical, against the +// scalar reference on extremal, random and smooth inputs; src is cut exactly at the footprint, so +// a read past it faults the bounds check, not just corrupts a neighbour. +func TestMaddKernelsAgainstScalar(t *testing.T) { + r := rand.New(rand.NewPCG(1, 2)) + taps := append([][]int16{}, vp9Taps...) + for range 200 { + taps = append(taps, randTaps(r)) + } + ran := 0 + for _, tp := range taps { + for _, w := range []int{4, 8, 16, 24, 32, 64} { + for _, h := range []int{1, 5, 8, 16} { + for _, vert := range []bool{false, true} { + ss := w + 16 + step := 1 + if vert { + step = ss + } + n := (h-1)*ss + w + 7*step + for pat := range 4 { + src := make([]byte, n) + for i := range src { + switch pat { + case 0: + src[i] = byte(r.IntN(256)) + case 1: + src[i] = byte(255 * (r.IntN(2))) + case 2: // the sign pattern of the taps maximises each partial sum + k := i % 8 + if vert { + k = i / ss % 8 + } + if (tp[k] > 0) == (i%2 == 0 || vert) { + src[i] = 255 + } + default: + src[i] = byte(100 + r.IntN(20)) + } + } + want := make([]byte, (h-1)*w+w) + FilterScalar(src, ss, want, w, w, h, step, tp) + for name, f := range map[string]func([]byte, int, []byte, int, int, int, int, []int16) bool{ + "wide": filterWide8, "narrow": filterNarrow8, + } { + got := make([]byte, len(want)) + if !f(src, ss, got, w, w, h, step, tp) { + continue + } + ran++ + if !bytes.Equal(got, want) { + t.Fatalf("%s w=%d h=%d vert=%v taps=%v pat=%d: kernel differs from scalar", name, w, h, vert, tp, pat) + } + } + } + } + } + } + } + if ran == 0 { + t.Fatal("no kernel ran") + } +} diff --git a/internal/pixel/filter_six_simd.go b/internal/pixel/filter_six_simd.go index 0f55543..d95896f 100644 --- a/internal/pixel/filter_six_simd.go +++ b/internal/pixel/filter_six_simd.go @@ -102,6 +102,9 @@ func filterNarrow8(src []byte, ss int, dst []byte, ds, w, h, step int, taps []in if len(taps) != 8 || w <= 0 || (w != 4 && w%8 != 0) || h <= 0 || ss < 0 || ds < 0 || step < 0 { return false } + if step == 1 && filterHorizMadd8(src, ss, dst, ds, w, h, taps) { + return true + } mode := narrow8Mode(taps) if mode == 0 { return false