diff --git a/go.mod b/go.mod index 36bdeff..41b3834 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/go-avkit/bitstream v0.4.0 github.com/go-avkit/h264 v0.15.0 github.com/go-avkit/h265 v0.24.2 + github.com/go-avkit/vpx v0.1.0 github.com/go-dsp/signal v0.2.0 github.com/go-fft/fft v0.45.0 github.com/go-simd/floats v0.44.0 diff --git a/go.sum b/go.sum index a95c751..42bd6dc 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,8 @@ github.com/go-avkit/h264 v0.15.0 h1:qS2p5P49/5IORABb/LX87Dsx3Ow65DsGv40GOVcstSU= github.com/go-avkit/h264 v0.15.0/go.mod h1:pV4PlD0loEiFsV9+A3tNZtCmbPjHoLTIKB7m1oGvREs= github.com/go-avkit/h265 v0.24.2 h1:w0ByM/ydnIBGqBn+b9HWBkAJidOSwUZD0m/iNBR907g= github.com/go-avkit/h265 v0.24.2/go.mod h1:zxEkIW5Tw0h1pi1KsoHbZaX1xneKIlQHV5qokikUNOk= +github.com/go-avkit/vpx v0.1.0 h1:W9qoz57q9yLf5FBSG+CZfT6GEV6H0ibxGjKY+aOKUYk= +github.com/go-avkit/vpx v0.1.0/go.mod h1:b4b8/60BTclv6gIz4q3QltkzUlBRkXW0z7DXOIoMM2Y= github.com/go-dsp/signal v0.2.0 h1:+566tdjkOtNctyqU+xzf7NRGYu4rR9GvCk4QtF9pYWY= github.com/go-dsp/signal v0.2.0/go.mod h1:V1WJie25RkckmxghlSe11czV9MfD7H8ba+QB0ZR1XCI= github.com/go-fft/fft v0.45.0 h1:i3ZxohNGFiwk5xBVIKZiU6iDIgf8OZdhfvQ1sLta1co= diff --git a/tools/go.sum b/tools/go.sum index a4004d1..3ffdd77 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -15,6 +15,8 @@ github.com/go-avkit/h264 v0.15.0 h1:qS2p5P49/5IORABb/LX87Dsx3Ow65DsGv40GOVcstSU= github.com/go-avkit/h264 v0.15.0/go.mod h1:pV4PlD0loEiFsV9+A3tNZtCmbPjHoLTIKB7m1oGvREs= github.com/go-avkit/h265 v0.24.2 h1:w0ByM/ydnIBGqBn+b9HWBkAJidOSwUZD0m/iNBR907g= github.com/go-avkit/h265 v0.24.2/go.mod h1:zxEkIW5Tw0h1pi1KsoHbZaX1xneKIlQHV5qokikUNOk= +github.com/go-avkit/vpx v0.1.0 h1:W9qoz57q9yLf5FBSG+CZfT6GEV6H0ibxGjKY+aOKUYk= +github.com/go-avkit/vpx v0.1.0/go.mod h1:b4b8/60BTclv6gIz4q3QltkzUlBRkXW0z7DXOIoMM2Y= github.com/go-dsp/signal v0.2.0 h1:+566tdjkOtNctyqU+xzf7NRGYu4rR9GvCk4QtF9pYWY= github.com/go-dsp/signal v0.2.0/go.mod h1:V1WJie25RkckmxghlSe11czV9MfD7H8ba+QB0ZR1XCI= github.com/go-fft/fft v0.45.0 h1:i3ZxohNGFiwk5xBVIKZiU6iDIgf8OZdhfvQ1sLta1co= diff --git a/vpx_diff_test.go b/vpx_diff_test.go new file mode 100644 index 0000000..b31faf1 --- /dev/null +++ b/vpx_diff_test.go @@ -0,0 +1,392 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package decode + +import ( + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + avx "github.com/go-avkit/vpx" + "github.com/go-avkit/vpx/vp8" + "github.com/go-avkit/vpx/vp9" + "github.com/thesyncim/govpx" +) + +// The differential lane (M0 step D0b of docs/design/vpx-decoder.md): the same packets go to +// govpx v0.5.3, which decode used until now, and to github.com/go-avkit/vpx, its port, and every +// step must agree: whether a picture comes out, whether it is flagged corrupt, the picture itself +// (size, chroma layout, bit depth and every visible sample) and the class of the error. The lane +// is test-only: nothing outside the tests imports go-avkit/vpx yet (D0c switches decode to it). + +// diffStep is what one decoder did with one packet. +type diffStep struct { + err string // class of the error, "" for none + shown bool // NextFrame returned a picture + corrupt bool // LastFrameCorrupted + pic [sha256.Size]byte +} + +// diffView is the part of an Image the comparison reads, whichever module produced it. +type diffView struct { + w, h, sub, depth int + y, u, v []byte + y16, u16, v16 []uint16 + ys, us, vs int +} + +// digest hashes the picture's header and its visible samples, cropped to the display size. +func (v diffView) digest() (sum [sha256.Size]byte) { + h := sha256.New() + put := func(n int) { binary.Write(h, binary.LittleEndian, int64(n)) } + put(v.w) + put(v.h) + put(v.sub) + put(v.depth) + cw, ch := v.w, v.h + switch v.sub { + case int(avx.Subsampling420): + cw, ch = (v.w+1)/2, (v.h+1)/2 + case int(avx.Subsampling422): + cw = (v.w + 1) / 2 + case int(avx.Subsampling440): + ch = (v.h + 1) / 2 + } + plane8 := func(p []byte, stride, w, hh int) { + for r := range hh { + if stride < w || r*stride+w > len(p) { + h.Write([]byte("short")) + return + } + h.Write(p[r*stride : r*stride+w]) + } + } + plane16 := func(p []uint16, stride, w, hh int) { + var b [2]byte + for r := range hh { + if stride < w || r*stride+w > len(p) { + h.Write([]byte("short")) + return + } + for _, s := range p[r*stride : r*stride+w] { + b[0], b[1] = byte(s), byte(s>>8) + h.Write(b[:]) + } + } + } + if v.depth == 0 || v.depth == 8 { + plane8(v.y, v.ys, v.w, v.h) + plane8(v.u, v.us, cw, ch) + plane8(v.v, v.vs, cw, ch) + } else { + plane16(v.y16, v.ys, v.w, v.h) + plane16(v.u16, v.us, cw, ch) + plane16(v.v16, v.vs, cw, ch) + } + h.Sum(sum[:0]) + return sum +} + +func viewGovpx(i govpx.Image) diffView { + return diffView{i.Width, i.Height, int(i.Subsampling), int(i.BitDepth), i.Y, i.U, i.V, i.Y16, i.U16, i.V16, i.YStride, i.UStride, i.VStride} +} + +func viewVpx(i avx.Image) diffView { + return diffView{i.Width, i.Height, int(i.Subsampling), int(i.BitDepth), i.Y, i.U, i.V, i.Y16, i.U16, i.V16, i.YStride, i.UStride, i.VStride} +} + +// sentinelPairs maps each error sentinel of go-avkit/vpx onto govpx's. +var sentinelPairs = []struct{ port, ref error }{ + {avx.ErrVP9NotImplemented, govpx.ErrVP9NotImplemented}, + {avx.ErrFrameRejected, govpx.ErrFrameRejected}, + {avx.ErrClosed, govpx.ErrClosed}, + {avx.ErrInvalidData, govpx.ErrInvalidData}, + {avx.ErrInvalidVP9Data, govpx.ErrInvalidVP9Data}, + {avx.ErrNeedKeyFrame, govpx.ErrNeedKeyFrame}, + {avx.ErrInvalidConfig, govpx.ErrInvalidConfig}, +} + +// errClass names the class decode gives an error (classifyVPX), one of its sentinels or "other". +func errClass(err error, port bool) string { + if err == nil { + return "" + } + if port { + for _, p := range sentinelPairs { + if errors.Is(err, p.port) { + err = p.ref + break + } + } + } + err = classifyVPX(err) + for _, c := range []struct { + e error + name string + }{{ErrUnsupported, "unsupported"}, {ErrOverLimit, "overlimit"}, {ErrClosed, "closed"}, {ErrBitstream, "bitstream"}} { + if errors.Is(err, c.e) { + return c.name + } + } + return "other" +} + +// diffPair is a govpx decoder and a go-avkit/vpx decoder built with the same options. +type diffPair struct { + ref func(pkt []byte, pts uint64) diffStep + port func(pkt []byte, pts uint64) diffStep + stop func() +} + +// guarded runs one decode and turns a panic into a step no comparison accepts. +func guarded(f func() diffStep) (s diffStep) { + defer func() { + if r := recover(); r != nil { + s = diffStep{err: fmt.Sprintf("PANIC %v", r)} + } + }() + return f() +} + +func newDiffPair(vp9on bool, threads int) (*diffPair, error) { + side := int(min(int64(fuzzConfig.frameMBs())*16, 1<<14-1)) + cfg := Config{Threads: threads} + if vp9on { + side = int(min(int64(fuzzConfig.frameMBs())*16, 1<<16)) + ref, err := govpx.NewVP9Decoder(vp9Options(cfg, side)) + if err != nil { + return nil, err + } + o := vp9.Options{MaxWidth: side, MaxHeight: side} + if threads >= 2 { + o.Threads, o.RowMT = threads, true + } + port, err := vp9.New(o) + if err != nil { + return nil, err + } + return &diffPair{ + ref: func(pkt []byte, pts uint64) diffStep { + return guarded(func() diffStep { + if err := ref.DecodeWithPTS(pkt, pts); err != nil { + return diffStep{err: errClass(err, false)} + } + img, ok := ref.NextFrame() + c, _ := ref.LastFrameCorrupted() + s := diffStep{shown: ok, corrupt: c} + if ok { + s.pic = viewGovpx(img).digest() + } + return s + }) + }, + port: func(pkt []byte, pts uint64) diffStep { + return guarded(func() diffStep { + if err := port.DecodeWithPTS(pkt, pts); err != nil { + return diffStep{err: errClass(err, true)} + } + img, ok := port.NextFrame() + c, _ := port.LastFrameCorrupted() + s := diffStep{shown: ok, corrupt: c} + if ok { + s.pic = viewVpx(img).digest() + } + return s + }) + }, + stop: func() { ref.Close(); port.Close() }, + }, nil + } + ref, err := govpx.NewVP8Decoder(vp8Options(cfg, side)) + if err != nil { + return nil, err + } + o := vp8.Options{MaxWidth: side, MaxHeight: side} + if threads >= 2 { + o.Threads = 2 + } + port, err := vp8.New(o) + if err != nil { + return nil, err + } + return &diffPair{ + ref: func(pkt []byte, pts uint64) diffStep { + return guarded(func() diffStep { + if err := ref.DecodeWithPTS(pkt, pts); err != nil { + return diffStep{err: errClass(err, false)} + } + img, ok := ref.NextFrame() + c, _ := ref.LastFrameCorrupted() + s := diffStep{shown: ok, corrupt: c} + if ok { + s.pic = viewGovpx(img).digest() + } + return s + }) + }, + port: func(pkt []byte, pts uint64) diffStep { + return guarded(func() diffStep { + if err := port.DecodeWithPTS(pkt, pts); err != nil { + return diffStep{err: errClass(err, true)} + } + img, ok := port.NextFrame() + c, _ := port.LastFrameCorrupted() + s := diffStep{shown: ok, corrupt: c} + if ok { + s.pic = viewVpx(img).digest() + } + return s + }) + }, + stop: func() { ref.Close(); port.Close() }, + }, nil +} + +// diffRun feeds the packets to both decoders and returns the first disagreement, or "". A packet +// that makes either decoder panic is a disagreement with itself. +func diffRun(vp9on bool, threads int, pkts [][]byte) string { + p, err := newDiffPair(vp9on, threads) + if err != nil { + return fmt.Sprintf("constructor: %v", err) + } + defer p.stop() + for i, pkt := range pkts { + a, b := p.ref(pkt, uint64(i)), p.port(pkt, uint64(i)) + if strings.HasPrefix(a.err, "PANIC") || strings.HasPrefix(b.err, "PANIC") || a != b { + return fmt.Sprintf("packet %d (%d bytes): govpx %+v, port %+v", i, len(pkt), short(a), short(b)) + } + } + return "" +} + +// short prints a step with its picture hash cut to eight hex digits. +func short(s diffStep) string { + return fmt.Sprintf("{err %q shown %v corrupt %v pic %x}", s.err, s.shown, s.corrupt, s.pic[:4]) +} + +// The comparison can tell: a picture differing by one sample, one chroma sample or one bit of +// header gives another digest, and every sentinel of the port falls in its govpx twin's class. +func TestVPXDiffCanTell(t *testing.T) { + base := diffView{w: 3, h: 3, y: make([]byte, 9), u: make([]byte, 4), v: make([]byte, 4), ys: 3, us: 2, vs: 2} + want := base.digest() + for name, mutate := range map[string]func(*diffView){ + "luma": func(v *diffView) { v.y = append([]byte(nil), v.y...); v.y[8] = 1 }, + "chroma": func(v *diffView) { v.v = append([]byte(nil), v.v...); v.v[3] = 1 }, + "width": func(v *diffView) { v.w = 2 }, + "sub": func(v *diffView) { v.sub = int(avx.Subsampling444) }, + "depth": func(v *diffView) { v.depth = 10 }, + } { + v := base + mutate(&v) + if v.digest() == want { + t.Errorf("a change of %s leaves the digest alone", name) + } + } + for _, p := range sentinelPairs { + if a, b := errClass(p.ref, false), errClass(p.port, true); a != b { + t.Errorf("%v: govpx class %q, port class %q", p.port, a, b) + } + } + if errClass(errors.New("x"), true) != "other" || errClass(nil, true) != "" { + t.Error("an unknown error is other, no error is empty") + } + if a, b := short(diffStep{err: "x"}), short(diffStep{}); a == b { + t.Error("short hides the error") + } +} + +// TestVPXDifferentialStreams: the committed streams are decoded identically, serial and threaded. +func TestVPXDifferentialStreams(t *testing.T) { + for _, s := range vpxStreams { + r, id := vpxTrack(t, s.name) + ss, err := r.Samples(id) + if err != nil { + t.Fatal(err) + } + var pkts [][]byte + for _, sm := range ss { + pkts = append(pkts, sm.Data) + } + for _, threads := range []int{0, 4} { + if d := diffRun(s.codec == "vp09", threads, pkts); d != "" { + t.Errorf("%s, %d threads: %s", s.name, threads, d) + } + } + } +} + +// TestVPXDifferentialVectors: libvpx's 376 vectors, frame by frame, serial and threaded (set +// LIBVPX_VECTORS_DIR as for TestLibvpxVectors). 4:4:0 is compared as pictures, not through Frame. +func TestVPXDifferentialVectors(t *testing.T) { + dir := os.Getenv("LIBVPX_VECTORS_DIR") + if dir == "" { + t.Skip("LIBVPX_VECTORS_DIR is not set: the differential lane over libvpx's vectors was NOT run") + } + identical := 0 + defer func() { t.Logf("%d of %d vectors identical, serial and with 4 threads", identical, libvpxVectors) }() + for _, name := range libvpxNames(t) { + t.Run(name, func(t *testing.T) { + path := filepath.Join(dir, name) + if !fileExists(path) { + t.Fatalf("%s is not in %s: this vector was NOT run", name, dir) + } + samples, err := libvpxSamples(path) + if err != nil { + t.Fatal(err) + } + ok := true + for _, threads := range []int{0, 4} { + if d := diffRun(!strings.HasPrefix(name, "vp80"), threads, samples); d != "" { + ok = false + t.Errorf("%d threads: %s", threads, d) + } + } + if ok { + identical++ + } + }) + } +} + +// diffSeeds adds the committed streams' packets, the first three of each, to a fuzz target. +func diffSeeds(f *testing.F, vp9on bool) { + for _, s := range vpxStreams { + if (s.codec == "vp09") != vp9on { + continue + } + r, id := vpxTrack(f, s.name) + ss, err := r.Samples(id) + if err != nil { + f.Fatal(err) + } + for _, sm := range ss[:min(3, len(ss))] { + f.Add(sm.Data) + } + } + f.Add(vp8Key(16383, 16383)) + f.Add(vp9Key(65536, 65536)) +} + +// FuzzVP8Differential and FuzzVP9Differential: whatever bytes a packet holds, both decoders +// agree on the outcome (the picture when there is one, otherwise the class of the error), and +// neither panics. The packet is sent twice, so that the second decode runs on the state the first +// left behind. +func FuzzVP8Differential(f *testing.F) { diffSeeds(f, false); fuzzDiff(f, false) } +func FuzzVP9Differential(f *testing.F) { diffSeeds(f, true); fuzzDiff(f, true) } + +func fuzzDiff(f *testing.F, vp9on bool) { + f.Fuzz(func(t *testing.T, b []byte) { + if len(b) == 0 { + return + } + if d := diffRun(vp9on, 0, [][]byte{b, b}); d != "" { + t.Fatal(d) + } + }) +}