diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7cae58f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,81 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + gofmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@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 + + test: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go vet ./... + - run: go build ./... + - run: go test -race -timeout 20m ./... + + # The parsers read files a tool or a server produced: the corpus in + # testdata/fuzz runs as ordinary tests above, this job also mutates it. + fuzz: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go test -timeout 10m -run XXX -fuzz FuzzParseY4MHeader -fuzztime 30s ./internal/bench + - run: go test -timeout 10m -run XXX -fuzz FuzzParseQuality -fuzztime 30s ./internal/bench + - run: go test -timeout 10m -run XXX -fuzz FuzzParsePaths -fuzztime 30s ./internal/bench + - run: go test -timeout 10m -run XXX -fuzz FuzzMatchedBytes -fuzztime 30s ./internal/bench + + # int is 32 bits here: a size converted to int before it is compared wraps + # only on this target. + arch-386: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: GOARCH=386 go vet ./... + - run: GOARCH=386 go test -timeout 20m ./... + + vuln: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go install golang.org/x/vuln/cmd/govulncheck@latest + - run: govulncheck ./... diff --git a/.gitignore b/.gitignore index 8dd1ac9..8d4ef14 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,15 @@ profile.cov go.work go.work.sum +# Clips are fetched by URL and checked against their SHA-256, never committed +*.y4m +*.y4m.part +*.part +*.mp4 +*.mkv +*.webm +*.ivf + # env file .env diff --git a/README.md b/README.md index 1185e0e..c754fe6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,85 @@ # vectorbench -Reproducible benchmark: frame-by-frame vectorisation (VTracer) against x264, x265, SVT-AV1 and VP9 at matched PSNR and VMAF + +Does vectorising a video frame by frame (VTracer) beat a video codec at the +same quality? `vectorbench` answers it per content class: cartoon, anime, +screen content and natural camera footage. It compares +VTracer with x264, x265, SVT-AV1 and VP9 at matched PSNR and matched VMAF. + +It records what it measured, with which tools, on which machine, at which +load. A figure that is interpolated between two encoder settings is marked +`est.`; a figure that is only a bound is marked `<=`; a quality no setting +reached is `n/a`. Nothing is rounded into a measured value. + +``` +go install github.com/go-avkit/vectorbench/cmd/vectorbench@latest + +vectorbench pin --work DIR # fetch the clips, print their SHA-256 +vectorbench run --work DIR --frames 24 # measure, write DIR/results.json +vectorbench report DIR/results.json # Markdown tables +``` + +## Tools + +| Tool | Pinned | Install | +|---|---|---| +| VTracer | 0.6.5 (MIT) | `cargo install vtracer --version 0.6.5 --locked` | +| resvg | 0.50.0 (MPL-2.0, rasterises the SVG for scoring) | `cargo install resvg --version 0.50.0 --locked` | +| ffmpeg | any recent build with libx264, libx265, libsvtav1, libvpx-vp9 and **libvmaf** | its version string is stored in the results | + +`run` refuses a VTracer or resvg of another version unless +`--allow-unpinned-tools` is given, and then stamps the difference into the +results. ffmpeg is not pinned (distributions differ); its full version line and +the encoder library versions are recorded instead. + +## Clips + +The manifest (`internal/bench/clips.json`) lists Xiph.org clips by URL and +SHA-256. Clips are **never committed**: `run` fetches the header and the first +24 frames with a Range request, hashes those bytes and refuses a mismatch (a +missing hash is also a refusal). `vectorbench pin` fills the hashes in; the +first pin trusts the server once, so read what it fetched. Classes: cartoon +(`GlassHalf`), anime (`SolLevanteFace`), screen (`Wikipedia`, `Slides1` and the +screen recordings `Debugging` and `MissionControlClip3`) and natural camera +footage (`KristenAndSara`, `in_to_tree` and `crowd_run`, a real 1080p50 clip). + +## What is measured + +- Size: encoded bytes; for vectors, the SVG bytes and their gzip size. +- Quality: PSNR and VMAF (libvmaf, `n_threads=4`) of the decoded or rasterised + frames against the source frames. +- Time: wall and CPU seconds of each encoder process and of the VTracer process + (sum over frames). The load average is read before the first run and after + the last, and stored. The run **refuses to start above `--max-load` (8)**; + `--load-waiver REASON` overrides it and stamps the reason into the results. + Pin the process to one core (`taskset -c N`) and say so with `--note`. +- Flicker proxy: path churn between consecutive frames, below. + +### Flicker proxy + +Frame-by-frame vectorisation has no temporal model, so the paths of frame N+1 +need not resemble those of frame N. For each consecutive pair, the paths of the +two SVGs are matched one to one, largest first, when their bounding boxes have +an IoU of at least 0.5 and their fill colours differ by at most 32 (Euclidean +RGB). `churn` is the fraction of paths that find no partner +(`1 - 2*matched/(n_prev+n_cur)`); the report also gives the unmatched area and +the mean centre shift of matched pairs. It is a **proxy**: it uses bounding +boxes and fills, not outlines, and says nothing about how visible a change is. +Zero means the structure is stable, not that the picture is. + +## Limits + +Prefixes of 2 to 24 frames, not whole clips: it measures per-frame cost and +quality, not rate control over a long GOP. Encoders run at fixed CRF settings, +so matched-quality sizes are interpolated (log size against quality) and marked. + +## Results + +`results/` holds the published results JSON, each with its tool versions, +machine and load. Rendered tables and the discussion are on the docs page +"Vector video vs codecs" of go-avkit/docs. + +## Licences + +The program is MIT. VTracer is MIT and resvg is MPL-2.0; both are run as +separate programs, never linked or vendored. No GPL tracer source was read or +used. diff --git a/cmd/vectorbench/main.go b/cmd/vectorbench/main.go new file mode 100644 index 0000000..68b32de --- /dev/null +++ b/cmd/vectorbench/main.go @@ -0,0 +1,222 @@ +// Command vectorbench measures frame-by-frame vectorisation (VTracer) against +// x264, x265, SVT-AV1 and VP9 at matched PSNR and VMAF, per content type. +// +// vectorbench run --work DIR [--frames N] [--only a,b] ... measure, write results.json +// vectorbench report results.json [--out FILE] render Markdown tables +// vectorbench pin --work DIR [--out clips.json] fetch the clips, print their SHA-256 +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime/debug" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/go-avkit/vectorbench/internal/bench" +) + +// Version is set by -ldflags "-X main.Version=v0.1.0"; a build from the module +// proxy reports its module version instead. +var Version = "" + +var osExit = os.Exit + +// newClient is the HTTP client for the clip downloads; tests replace it. +var newClient = func() *http.Client { return &http.Client{Timeout: 30 * time.Minute} } + +func version() string { + if Version != "" { + return Version + } + return moduleVersion(debug.ReadBuildInfo()) +} + +// moduleVersion is the version the module proxy stamped into a build, or "dev". +func moduleVersion(bi *debug.BuildInfo, ok bool) string { + if ok && bi.Main.Version != "" && bi.Main.Version != "(devel)" { + return bi.Main.Version + } + return "dev" +} + +// toolPins is the pin list a run checks; tests replace it. +var toolPins = bench.ToolPins + +func main() { + if err := RootCmd().Execute(); err != nil { + fmt.Fprintln(os.Stderr, "vectorbench:", err) + osExit(1) + } +} + +// RootCmd builds the command tree. +func RootCmd() *cobra.Command { + root := &cobra.Command{ + Use: "vectorbench", + Short: "Benchmark frame-by-frame vectorisation against video codecs at matched quality", + SilenceUsage: true, + SilenceErrors: true, + Version: version(), + } + root.AddCommand(runCmd(), reportCmd(), pinCmd()) + return root +} + +func runCmd() *cobra.Command { + var ( + work, only, note, waiver, clipsFile string + frames, jobs int + maxLoad float64 + ffmpeg, vtracer, resvg string + unpinned bool + ) + cmd := &cobra.Command{ + Use: "run", + Short: "Fetch the clips, encode and vectorise them, measure PSNR and VMAF, write results.json", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if work == "" { + return errors.New("--work is required") + } + clips, err := loadClips(clipsFile) + if err != nil { + return err + } + pins, err := toolPins() + if err != nil { + return err + } + cfg := bench.Config{ + Work: work, Frames: frames, Clips: clips, Variant: bench.DefaultVariants(), Jobs: jobs, + FFmpeg: ffmpeg, VTracer: vtracer, Resvg: resvg, + MaxLoad: maxLoad, LoadWaiver: waiver, AllowUnpinned: unpinned, Note: note, + Version: version(), Log: cmd.ErrOrStderr(), Load: bench.SystemLoad, Pins: pins, + Client: newClient(), + } + if only != "" { + cfg.Only = strings.Split(only, ",") + } + res, err := bench.Execute(cmd.Context(), cfg) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "wrote %s (%d runs)\n", filepath.Join(work, "results.json"), len(res.Runs)) + return nil + }, + } + f := cmd.Flags() + f.StringVar(&work, "work", "", "durable working directory for clips, frames and encodes (required)") + f.IntVar(&frames, "frames", 24, "frames per clip (2 to 24)") + f.StringVar(&only, "only", "", "comma-separated clip names (default all)") + f.IntVar(&jobs, "jobs", 1, "parallel VTracer processes (1 keeps timings honest)") + f.StringVar(&ffmpeg, "ffmpeg", "ffmpeg", "ffmpeg binary (with libx264, libx265, libsvtav1, libvpx-vp9, libvmaf)") + f.StringVar(&vtracer, "vtracer", "vtracer", "vtracer binary") + f.StringVar(&resvg, "resvg", "resvg", "resvg binary") + f.Float64Var(&maxLoad, "max-load", 8, "refuse to start when the one-minute load is above this") + f.StringVar(&waiver, "load-waiver", "", "why a run above --max-load goes ahead (stamped into the results)") + f.BoolVar(&unpinned, "allow-unpinned-tools", false, "accept VTracer or resvg versions other than the pinned ones") + f.StringVar(¬e, "note", "", "free text stored in the results, e.g. how the process was pinned to a core") + f.StringVar(&clipsFile, "clips", "", "clip manifest to use instead of the embedded one") + return cmd +} + +func loadClips(path string) ([]bench.Clip, error) { + if path == "" { + return bench.Manifest() + } + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return bench.ParseManifest(b) +} + +func reportCmd() *cobra.Command { + var out string + cmd := &cobra.Command{ + Use: "report RESULTS.json", + Short: "Render a results file as Markdown tables", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + b, err := os.ReadFile(args[0]) + if err != nil { + return err + } + res, err := bench.ParseResults(b) + if err != nil { + return err + } + var w io.Writer = cmd.OutOrStdout() + if out != "" { + f, err := os.Create(out) + if err != nil { + return err + } + defer f.Close() + w = f + } + return bench.Render(w, res) + }, + } + cmd.Flags().StringVar(&out, "out", "", "write to this file instead of standard output") + return cmd +} + +func pinCmd() *cobra.Command { + var work, out, clipsFile string + var repin bool + cmd := &cobra.Command{ + Use: "pin", + Short: "Fetch each clip's first frames and write the manifest with their SHA-256", + Long: `pin downloads the header and first 24 frames of every clip (a Range request), +computes the SHA-256 of those bytes and writes the manifest with the hashes +filled in. A clip that already has a hash is checked, not overwritten, unless +--repin is given. Read what was fetched before committing the result: the +first pin trusts the server once.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if work == "" { + return errors.New("--work is required") + } + clips, err := loadClips(clipsFile) + if err != nil { + return err + } + client := newClient() + for i, c := range clips { + dest := filepath.Join(work, c.Name, "prefix.y4m") + got, err := bench.FetchPrefix(cmd.Context(), client, c.URL, bench.PinFrames, dest) + if err != nil { + return err + } + if c.SHA256 != "" && c.SHA256 != got && !repin { + return fmt.Errorf("%s: pinned %s, server now serves %s (use --repin to accept)", c.Name, c.SHA256, got) + } + clips[i].SHA256 = got + fmt.Fprintf(cmd.ErrOrStderr(), "%s %s\n", got, c.Name) + } + // A list of plain strings and numbers always marshals. + js, _ := json.MarshalIndent(clips, "", " ") + js = append(js, '\n') + if out == "" { + _, err = cmd.OutOrStdout().Write(js) + return err + } + return os.WriteFile(out, js, 0o644) + }, + } + f := cmd.Flags() + f.StringVar(&work, "work", "", "durable working directory (required)") + f.StringVar(&out, "out", "", "write the manifest here (default standard output)") + f.StringVar(&clipsFile, "clips", "", "manifest to start from instead of the embedded one") + f.BoolVar(&repin, "repin", false, "accept a hash that differs from the pinned one") + return cmd +} diff --git a/cmd/vectorbench/main_test.go b/cmd/vectorbench/main_test.go new file mode 100644 index 0000000..77f29c3 --- /dev/null +++ b/cmd/vectorbench/main_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-avkit/vectorbench/internal/bench" +) + +func execute(args ...string) (string, string, error) { + cmd := RootCmd() + var out, errb bytes.Buffer + cmd.SetOut(&out) + cmd.SetErr(&errb) + cmd.SetArgs(args) + err := cmd.Execute() + return out.String(), errb.String(), err +} + +func TestReport(t *testing.T) { + res := bench.Results{ + Schema: bench.SchemaVersion, Tool: "t", Frames: 2, Started: time.Unix(0, 0), Finished: time.Unix(1, 0), + Clips: []bench.ClipInfo{{Name: "c", Class: "screen", Width: 2, Height: 2, FPS: 30}}, + Runs: []bench.Run{{Clip: "c", Class: "screen", Variant: "x264 crf23", Family: "x264", Frames: 2, Bytes: 10, PSNR: 40, VMAF: 90}}, + } + js, _ := json.Marshal(res) + dir := t.TempDir() + in := filepath.Join(dir, "r.json") + if err := os.WriteFile(in, js, 0o644); err != nil { + t.Fatal(err) + } + out, _, err := execute("report", in) + if err != nil || !strings.Contains(out, "x264 crf23") { + t.Fatalf("%v\n%s", err, out) + } + dest := filepath.Join(dir, "r.md") + if _, _, err := execute("report", in, "--out", dest); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(dest); !strings.Contains(string(b), "x264 crf23") { + t.Fatal("--out wrote nothing") + } +} + +func TestErrors(t *testing.T) { + dir := t.TempDir() + bad := filepath.Join(dir, "bad.json") + _ = os.WriteFile(bad, []byte("{}"), 0o644) + cases := [][]string{ + {"report"}, + {"report", filepath.Join(dir, "missing.json")}, + {"report", bad}, + {"run"}, + {"run", "--work", dir, "--clips", filepath.Join(dir, "missing.json")}, + {"pin"}, + {"run", "--bogus"}, + {"nothing"}, + } + for _, args := range cases { + if _, _, err := execute(args...); err == nil { + t.Errorf("%v succeeded", args) + } + } +} + +func TestRunRefusesOneFrame(t *testing.T) { + _, _, err := execute("run", "--work", t.TempDir(), "--frames", "1") + if err == nil || !strings.Contains(err.Error(), "frames") { + t.Fatalf("%v", err) + } +} + +func TestVersionAndMain(t *testing.T) { + out, _, err := execute("--version") + if err != nil || !strings.Contains(out, "vectorbench") { + t.Fatalf("%v %q", err, out) + } + Version = "v9.9.9" + defer func() { Version = "" }() + if version() != "v9.9.9" { + t.Fatal("ldflags version ignored") + } +} + +func TestMainExits(t *testing.T) { + code := -1 + osExit = func(c int) { code = c } + defer func() { osExit = os.Exit }() + old := os.Args + defer func() { os.Args = old }() + os.Args = []string{"vectorbench", "nothing"} + main() + if code != 1 { + t.Fatalf("exit %d", code) + } +} diff --git a/cmd/vectorbench/pin_test.go b/cmd/vectorbench/pin_test.go new file mode 100644 index 0000000..4727392 --- /dev/null +++ b/cmd/vectorbench/pin_test.go @@ -0,0 +1,176 @@ +package main + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime/debug" + "strings" + "testing" + + "github.com/go-avkit/vectorbench/internal/bench" +) + +func y4m(frames int) []byte { + b := []byte("YUV4MPEG2 W4 H2 F1:1 C420\n") + for i := 0; i < frames; i++ { + b = append(b, "FRAME\n"...) + b = append(b, make([]byte, 12)...) + } + return b +} + +// pinFixture serves one clip over TLS and writes a manifest naming it. +func pinFixture(t *testing.T, sha string) (manifest, work string) { + t.Helper() + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write(y4m(24)) + })) + t.Cleanup(srv.Close) + old := newClient + newClient = srv.Client + t.Cleanup(func() { newClient = old }) + dir := t.TempDir() + js, _ := json.Marshal([]map[string]any{{"name": "c1", "class": "screen", "desc": "d", "url": srv.URL, "fps": 30, "sha256": sha}}) + manifest = filepath.Join(dir, "clips.json") + if err := os.WriteFile(manifest, js, 0o644); err != nil { + t.Fatal(err) + } + return manifest, filepath.Join(dir, "work") +} + +func TestPin(t *testing.T) { + manifest, work := pinFixture(t, "") + out, errb, err := execute("pin", "--work", work, "--clips", manifest) + if err != nil { + t.Fatal(err) + } + var cs []map[string]any + if err := json.Unmarshal([]byte(out), &cs); err != nil || len(cs) != 1 { + t.Fatalf("%v %q", err, out) + } + sha, _ := cs[0]["sha256"].(string) + if len(sha) != 64 || !strings.Contains(errb, sha+" c1") { + t.Fatalf("sha %q, stderr %q", sha, errb) + } + // --out writes the manifest instead of printing it + dest := filepath.Join(t.TempDir(), "m.json") + out, _, err = execute("pin", "--work", work, "--clips", manifest, "--out", dest) + if err != nil || out != "" { + t.Fatalf("%v %q", err, out) + } + if b, _ := os.ReadFile(dest); !strings.Contains(string(b), sha) { + t.Fatalf("manifest not written: %s", b) + } + // a pinned clip whose hash still matches is accepted + manifest2, work2 := pinFixture(t, sha) + if _, _, err := execute("pin", "--work", work2, "--clips", manifest2); err != nil { + t.Fatal(err) + } +} + +func TestPinRefusals(t *testing.T) { + manifest, work := pinFixture(t, strings.Repeat("0", 64)) + _, _, err := execute("pin", "--work", work, "--clips", manifest) + if err == nil || !strings.Contains(err.Error(), "server now serves") || !strings.Contains(err.Error(), "c1") { + t.Fatalf("%v", err) + } + out, _, err := execute("pin", "--work", work, "--clips", manifest, "--repin") + if err != nil || strings.Contains(out, strings.Repeat("0", 64)) { + t.Fatalf("%v %s", err, out) + } + // the manifest cannot be written + dir := t.TempDir() + if _, _, err := execute("pin", "--work", work, "--clips", manifest, "--repin", "--out", dir); err == nil { + t.Fatal("wrote to a directory") + } + // nothing to fetch from + srv := httptest.NewTLSServer(http.NotFoundHandler()) + srv.Close() + old := newClient + newClient = srv.Client + defer func() { newClient = old }() + js, _ := json.Marshal([]map[string]any{{"name": "c1", "class": "screen", "url": srv.URL, "fps": 30}}) + m := filepath.Join(dir, "m.json") + os.WriteFile(m, js, 0o644) + if _, _, err := execute("pin", "--work", work+"2", "--clips", m); err == nil { + t.Fatal("fetched from a closed server") + } + if _, _, err := execute("pin", "--work", work, "--clips", filepath.Join(dir, "none.json")); err == nil { + t.Fatal("missing manifest accepted") + } +} + +func TestModuleVersion(t *testing.T) { + mk := func(v string) *debug.BuildInfo { return &debug.BuildInfo{Main: debug.Module{Version: v}} } + for _, c := range []struct { + bi *debug.BuildInfo + ok bool + want string + }{ + {mk("v1.2.3"), true, "v1.2.3"}, + {mk("v1.2.3"), false, "dev"}, + {mk(""), true, "dev"}, + {mk("(devel)"), true, "dev"}, + } { + if got := moduleVersion(c.bi, c.ok); got != c.want { + t.Errorf("%+v %v: %q", c.bi.Main, c.ok, got) + } + } +} + +func TestRunRefusesBrokenPins(t *testing.T) { + old := toolPins + toolPins = func() ([]bench.ToolPin, error) { return nil, errors.New("pins broken") } + defer func() { toolPins = old }() + if _, _, err := execute("run", "--work", t.TempDir()); err == nil || !strings.Contains(err.Error(), "pins broken") { + t.Fatalf("%v", err) + } +} + +func TestReportOutIsADirectory(t *testing.T) { + dir := t.TempDir() + good := filepath.Join(dir, "g.json") + os.WriteFile(good, []byte(`{"schema":1,"runs":[{"clip":"c","class":"screen","variant":"v","family":"x264","frames":2,"bytes":1}]}`), 0o644) + if _, _, err := execute("report", good, "--out", dir); err == nil || !strings.Contains(err.Error(), dir) { + t.Fatalf("%v", err) + } +} + +func TestRunMessages(t *testing.T) { + dir := t.TempDir() + bad := filepath.Join(dir, "bad.json") + os.WriteFile(bad, []byte("[]"), 0o644) + // --clips keeps a missed refusal from reaching the network + for _, c := range []string{"run", "pin"} { + if _, _, err := execute(c, "--clips", bad); err == nil || !strings.Contains(err.Error(), "--work is required") { + t.Fatalf("%s: %v", c, err) + } + } + if _, _, err := execute("run", "--work", dir, "--clips", bad); err == nil || !strings.Contains(err.Error(), "empty") { + t.Fatalf("%v", err) + } + if _, _, err := execute("run", "--work", dir, "--clips", filepath.Join(dir, "none.json")); err == nil || !strings.Contains(err.Error(), "none.json") { + t.Fatalf("%v", err) + } + // with the load waived, the first tool that cannot start is named + _, _, err := execute("run", "--work", filepath.Join(dir, "w"), "--only", "a,b", "--max-load", "1e9", + "--load-waiver", "test host has no load average on windows", "--ffmpeg", filepath.Join(dir, "no-ffmpeg")) + if err == nil || !strings.Contains(err.Error(), "ffmpeg") { + t.Fatalf("%v", err) + } + if _, _, err := execute("report", bad); err == nil || !strings.Contains(err.Error(), "results") { + t.Fatalf("%v", err) + } + if _, _, err := execute("report", filepath.Join(dir, "none.json")); err == nil || !strings.Contains(err.Error(), "none.json") { + t.Fatalf("%v", err) + } + good := filepath.Join(dir, "g.json") + os.WriteFile(good, []byte(`{"schema":1,"runs":[{"clip":"c","class":"screen","variant":"v","family":"x264","frames":2,"bytes":1}]}`), 0o644) + if _, _, err := execute("report", good, "--out", dir); err == nil { + t.Fatal("wrote the report to a directory") + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c033eec --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module github.com/go-avkit/vectorbench + +go 1.27.4 + +require github.com/spf13/cobra v1.10.2 + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a6ee3e0 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/bench/churn.go b/internal/bench/churn.go new file mode 100644 index 0000000..54c1b87 --- /dev/null +++ b/internal/bench/churn.go @@ -0,0 +1,178 @@ +package bench + +import ( + "math" + "sort" +) + +// Matching parameters of the flicker proxy. A path of frame t is the "same" +// path as one of frame t+1 when their fill colours are within ColourTol (RGB +// Euclidean distance) and their bounding boxes overlap with an IoU of at +// least MinIoU. The thresholds are stated, not tuned: the proxy is a measure of +// segmentation stability, not of perceived flicker. +const ( + ColourTol = 32.0 + MinIoU = 0.5 + cellSize = 64.0 +) + +// Churn is the change between two consecutive frames' paths. +type Churn struct { + Prev, Cur, Matched int + // Dice churn: 1 - 2*Matched/(Prev+Cur). 0 = same segmentation, 1 = nothing + // in common. Defined as 0 for two empty frames. + Churn float64 + // AreaUnmatched is the share of the bounding-box area of both frames that + // belongs to unmatched paths. + AreaUnmatched float64 + // MeanColourDist and MeanShift are over the matched pairs: the RGB distance + // and the displacement of the box centre, in pixels. + MeanColourDist, MeanShift float64 +} + +type cellKey struct{ x, y int } + +// MatchPaths pairs the paths of two consecutive frames greedily, largest +// first, each path of prev taking the free path of cur with the highest IoU +// among those within the colour tolerance. +func MatchPaths(prev, cur []Path) Churn { + c := Churn{Prev: len(prev), Cur: len(cur)} + grid := map[cellKey][]int{} + for j, p := range cur { + for _, k := range cells(p) { + grid[k] = append(grid[k], j) + } + } + order := make([]int, len(prev)) + for i := range order { + order[i] = i + } + sort.SliceStable(order, func(a, b int) bool { return prev[order[a]].Area() > prev[order[b]].Area() }) + taken := make([]bool, len(cur)) + matchedPrev := make([]bool, len(prev)) + var colSum, shiftSum float64 + var areaMatched float64 + for _, i := range order { + p := prev[i] + best, bestIoU := -1, MinIoU + seen := map[int]bool{} + for _, k := range cells(p) { + for _, j := range grid[k] { + if taken[j] || seen[j] { + continue + } + seen[j] = true + if colourDist(p, cur[j]) > ColourTol { + continue + } + if iou := IoU(p, cur[j]); iou >= bestIoU { + best, bestIoU = j, iou + } + } + } + if best < 0 { + continue + } + taken[best] = true + matchedPrev[i] = true + c.Matched++ + colSum += colourDist(p, cur[best]) + shiftSum += math.Hypot(p.CX()-cur[best].CX(), p.CY()-cur[best].CY()) + areaMatched += p.Area() + cur[best].Area() + } + if n := c.Prev + c.Cur; n > 0 { + c.Churn = 1 - 2*float64(c.Matched)/float64(n) + } + var total float64 + for _, p := range prev { + total += p.Area() + } + for _, p := range cur { + total += p.Area() + } + if total > 0 { + c.AreaUnmatched = 1 - areaMatched/total + if c.AreaUnmatched < 0 { + c.AreaUnmatched = 0 + } + } + if c.Matched > 0 { + c.MeanColourDist = colSum / float64(c.Matched) + c.MeanShift = shiftSum / float64(c.Matched) + } + return c +} + +// IoU is the intersection over union of two bounding boxes (0 when either is +// empty). +func IoU(a, b Path) float64 { + w := math.Min(a.X1, b.X1) - math.Max(a.X0, b.X0) + h := math.Min(a.Y1, b.Y1) - math.Max(a.Y0, b.Y0) + if w < 0 || h < 0 { + return 0 + } + inter := w * h + union := a.Area() + b.Area() - inter + if union <= 0 { + // Two degenerate boxes: equal when they coincide. + if a.X0 == b.X0 && a.X1 == b.X1 && a.Y0 == b.Y0 && a.Y1 == b.Y1 { + return 1 + } + return 0 + } + return inter / union +} + +func colourDist(a, b Path) float64 { + dr, dg, db := float64(a.R)-float64(b.R), float64(a.G)-float64(b.G), float64(a.B)-float64(b.B) + return math.Sqrt(dr*dr + dg*dg + db*db) +} + +// cells lists the grid cells a box touches, bounded so that a page-sized box +// does not enumerate millions of cells: boxes larger than 32x32 cells are +// indexed by their four corners and their centre only, which is enough to find +// any box of IoU >= 0.5 with them. +func cells(p Path) []cellKey { + x0, y0 := int(math.Floor(p.X0/cellSize)), int(math.Floor(p.Y0/cellSize)) + x1, y1 := int(math.Floor(p.X1/cellSize)), int(math.Floor(p.Y1/cellSize)) + if x1-x0 >= 32 || y1-y0 >= 32 { + cx, cy := int(math.Floor(p.CX()/cellSize)), int(math.Floor(p.CY()/cellSize)) + return []cellKey{{x0, y0}, {x1, y0}, {x0, y1}, {x1, y1}, {cx, cy}} + } + out := make([]cellKey, 0, (x1-x0+1)*(y1-y0+1)) + for y := y0; y <= y1; y++ { + for x := x0; x <= x1; x++ { + out = append(out, cellKey{x, y}) + } + } + return out +} + +// ChurnSummary is the mean of the consecutive-frame Churn values of a clip. +type ChurnSummary struct { + Pairs int `json:"pairs"` + Churn float64 `json:"churn"` + AreaUnmatched float64 `json:"area_unmatched"` + MeanColourDist float64 `json:"mean_colour_dist"` + MeanShift float64 `json:"mean_shift_px"` +} + +// Summarise averages the per-pair values. +func Summarise(cs []Churn) ChurnSummary { + s := ChurnSummary{Pairs: len(cs)} + if len(cs) == 0 { + return s + } + for _, c := range cs { + s.Churn += c.Churn + s.AreaUnmatched += c.AreaUnmatched + s.MeanColourDist += c.MeanColourDist + s.MeanShift += c.MeanShift + } + n := float64(len(cs)) + s.Churn /= n + s.AreaUnmatched /= n + s.MeanColourDist /= n + s.MeanShift /= n + return s +} diff --git a/internal/bench/churn_test.go b/internal/bench/churn_test.go new file mode 100644 index 0000000..caa43cf --- /dev/null +++ b/internal/bench/churn_test.go @@ -0,0 +1,91 @@ +package bench + +import ( + "math" + "testing" +) + +func box(x0, y0, x1, y1 float64, r, g, b uint8) Path { + return Path{R: r, G: g, B: b, X0: x0, Y0: y0, X1: x1, Y1: y1} +} + +func TestMatchPathsIdenticalAndDisjoint(t *testing.T) { + a := []Path{box(0, 0, 10, 10, 255, 0, 0), box(20, 20, 30, 30, 0, 255, 0), box(0, 0, 500, 400, 9, 9, 9)} + c := MatchPaths(a, a) + if c.Matched != 3 || c.Churn != 0 || c.AreaUnmatched != 0 || c.MeanShift != 0 || c.MeanColourDist != 0 { + t.Fatalf("%+v", c) + } + b := []Path{box(100, 100, 110, 110, 255, 0, 0)} + c = MatchPaths(a, b) + if c.Matched != 0 || c.Churn != 1 || c.AreaUnmatched != 1 { + t.Fatalf("%+v", c) + } + if c := MatchPaths(nil, nil); c.Churn != 0 || c.Matched != 0 { + t.Fatalf("empty: %+v", c) + } + if c := MatchPaths(a, nil); c.Churn != 1 { + t.Fatalf("one empty: %+v", c) + } +} + +func TestMatchPathsColourAndShift(t *testing.T) { + prev := []Path{box(0, 0, 10, 10, 100, 100, 100)} + // same box, colour moved by 10 (within tolerance), shifted by 1 px + cur := []Path{box(1, 0, 11, 10, 106, 108, 100)} + c := MatchPaths(prev, cur) + if c.Matched != 1 || math.Abs(c.MeanColourDist-10) > 1e-9 || math.Abs(c.MeanShift-1) > 1e-9 { + t.Fatalf("%+v", c) + } + // colour jump beyond the tolerance: same place, no match + far := []Path{box(0, 0, 10, 10, 200, 100, 100)} + if c := MatchPaths(prev, far); c.Matched != 0 { + t.Fatalf("colour tolerance ignored: %+v", c) + } + // overlap below the IoU threshold: no match + low := []Path{box(8, 0, 18, 10, 100, 100, 100)} + if c := MatchPaths(prev, low); c.Matched != 0 { + t.Fatalf("IoU threshold ignored: %+v", c) + } +} + +func TestMatchPathsOneToOne(t *testing.T) { + prev := []Path{box(0, 0, 10, 10, 0, 0, 0), box(0, 0, 10, 10, 0, 0, 0)} + cur := []Path{box(0, 0, 10, 10, 0, 0, 0)} + c := MatchPaths(prev, cur) + if c.Matched != 1 { + t.Fatalf("a path matched twice: %+v", c) + } + if want := 1 - 2.0/3; math.Abs(c.Churn-want) > 1e-12 { + t.Fatalf("churn %v want %v", c.Churn, want) + } +} + +func TestIoUDegenerate(t *testing.T) { + p := box(1, 1, 1, 1, 0, 0, 0) + if IoU(p, p) != 1 { + t.Error("coinciding points") + } + if IoU(p, box(2, 2, 2, 2, 0, 0, 0)) != 0 { + t.Error("distinct points") + } +} + +func TestHugeBoxIsIndexedBounded(t *testing.T) { + big := box(0, 0, 1e7, 1e7, 1, 2, 3) + if n := len(cells(big)); n != 5 { + t.Fatalf("%d cells", n) + } + if c := MatchPaths([]Path{big}, []Path{big}); c.Matched != 1 { + t.Fatalf("%+v", c) + } +} + +func TestSummarise(t *testing.T) { + s := Summarise([]Churn{{Churn: 0.2, AreaUnmatched: 0.1, MeanShift: 2}, {Churn: 0.4, AreaUnmatched: 0.3, MeanShift: 4}}) + if s.Pairs != 2 || math.Abs(s.Churn-0.3) > 1e-12 || math.Abs(s.AreaUnmatched-0.2) > 1e-12 || s.MeanShift != 3 { + t.Fatalf("%+v", s) + } + if Summarise(nil).Pairs != 0 { + t.Fatal("empty") + } +} diff --git a/internal/bench/clips.json b/internal/bench/clips.json new file mode 100644 index 0000000..76b633b --- /dev/null +++ b/internal/bench/clips.json @@ -0,0 +1,74 @@ +[ + { + "name": "GlassHalf", + "class": "cartoon", + "desc": "toon-shaded animation, 1080p24", + "url": "https://media.xiph.org/video/aomctc/test_set/b1_syn/GlassHalf_1920x1080p_24p_8bit_420.y4m", + "fps": 24, + "sha256": "90ca10235d0b4037dfeffe49289ec43f2d154b70548e702457c5c96675969269" + }, + { + "name": "SolLevanteFace", + "class": "anime", + "desc": "hand-drawn anime, 1080p24", + "url": "https://media.xiph.org/video/aomctc/test_set/b1_syn/SolLevanteFace_sdr_1920x1080_24_10bit.y4m", + "fps": 24, + "sha256": "91b5e83125d48b4505b1cdb5844f4209f02bc8801a1688bea34d7d603ac81f46" + }, + { + "name": "Wikipedia", + "class": "screen", + "desc": "screen capture: web page with text, 1080p30", + "url": "https://media.xiph.org/video/aomctc/test_set/b2_scc/Wikipedia_1920x1080p30.y4m", + "fps": 30, + "sha256": "61aee8ff577825b5049705d5326d801167af752c17305c977a4b5c51ac2c0fe3" + }, + { + "name": "Slides1", + "class": "screen", + "desc": "screen capture: slides, 1080p30", + "url": "https://media.xiph.org/video/aomctc/test_set/b2_scc/Slides1_1920x1080_30fps_8bit_420.y4m", + "fps": 30, + "sha256": "b2963da356b2c2479284bfb51416c0f731cd7aa856ffc4c9af17e65b8ee34aa9" + }, + { + "name": "Debugging", + "class": "screen", + "desc": "screen recording: IDE debugging session, 1080p30", + "url": "https://media.xiph.org/video/aomctc/test_set/b2_scc/Debugging_1920x1080_30fps_8bit_420.y4m", + "fps": 30, + "sha256": "6c974572f4ce234fdc38bfdc60d0a2bb6bfc2e087849b406513c4da16636b3f5" + }, + { + "name": "MissionControlClip3", + "class": "screen", + "desc": "screen recording: desktop with window animations, 1080p60", + "url": "https://media.xiph.org/video/aomctc/test_set/b2_scc/MissionControlClip3_1920x1080_60_420.y4m", + "fps": 60, + "sha256": "09aaa381ab2b71e2ea115f91786d96ac087b1658ecba0da55fa7490c87969047" + }, + { + "name": "KristenAndSara", + "class": "natural", + "desc": "camera: video call, fixed camera, 720p60", + "url": "https://media.xiph.org/video/derf/y4m/KristenAndSara_1280x720_60.y4m", + "fps": 60, + "sha256": "1e17fa7d5c4d978cf2770b8c7139fc24ac54f48b243080ca00a3f7cf1e5f7b62" + }, + { + "name": "in_to_tree", + "class": "natural", + "desc": "camera: tree texture, camera motion, 720p50", + "url": "https://media.xiph.org/video/derf/y4m/in_to_tree_420_720p50.y4m", + "fps": 50, + "sha256": "8632ffecaf8431f6a6afeb121a69e70d04f153d829e14ddf1f63065cbb6fc95a" + }, + { + "name": "crowd_run", + "class": "natural", + "desc": "camera: crowd running, dense detail, 1080p50", + "url": "https://media.xiph.org/video/derf/y4m/crowd_run_1080p50.y4m", + "fps": 50, + "sha256": "829d214298b7708b6bfcad524c73f4d415f9d2a379db62e0096e9151bce00bdd" + } +] diff --git a/internal/bench/edge2_test.go b/internal/bench/edge2_test.go new file mode 100644 index 0000000..11857c0 --- /dev/null +++ b/internal/bench/edge2_test.go @@ -0,0 +1,146 @@ +package bench + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync/atomic" + "testing" +) + +func TestY4MHeaderBounds(t *testing.T) { + base := "YUV4MPEG2 W4 H2 C420" + pad := func(n int) []byte { // a header whose newline is at index n + return []byte(base + strings.Repeat(" ", n-len(base)) + "\n") + } + if _, err := ParseY4MHeader(pad(MaxHeaderLen - 1)); err != nil { + t.Fatalf("newline at %d: %v", MaxHeaderLen-1, err) + } + if _, err := ParseY4MHeader(pad(MaxHeaderLen)); err == nil || !strings.Contains(err.Error(), "longer") { + t.Fatalf("newline at %d: %v", MaxHeaderLen, err) + } + long := []byte(strings.Repeat("a", MaxHeaderLen)) + if _, err := ParseY4MHeader(long); err == nil || !strings.Contains(err.Error(), "longer") { + t.Fatalf("%v", err) + } + if _, err := ParseY4MHeader(long[:MaxHeaderLen-1]); err == nil || !strings.Contains(err.Error(), "no newline") { + t.Fatalf("%v", err) + } + for _, h := range []string{"H0", "H-1", "H16385", "Hx"} { + if _, err := ParseY4MHeader([]byte("YUV4MPEG2 W4 " + h + "\n")); err == nil || !strings.Contains(err.Error(), "bad height") { + t.Errorf("%s: %v", h, err) + } + } + for _, w := range []string{"W0", "W-1", "W16385", "Wx"} { + if _, err := ParseY4MHeader([]byte("YUV4MPEG2 H4 " + w + "\n")); err == nil || !strings.Contains(err.Error(), "bad width") { + t.Errorf("%s: %v", w, err) + } + } + if h, err := ParseY4MHeader([]byte("YUV4MPEG2 W16384 H16384 Cmono\n")); err != nil || h.Height != MaxDimension { + t.Fatalf("%v", err) + } + if _, err := ParseY4MHeader([]byte("YUV4MPEG2 W4 H2 C420alpha\n")); err == nil || !strings.Contains(err.Error(), "alpha planes") { + t.Fatalf("%v", err) + } + if _, err := (Y4M{Width: 4, Height: 2, Chroma: "bogus", HeaderLen: 10}).PrefixLen(1); err == nil || !strings.Contains(err.Error(), "chroma") { + t.Fatalf("%v", err) + } + if f := (Y4M{FPSNum: 5}).FPS(); f != 0 { + t.Fatalf("%v", f) + } + if f := (Y4M{FPSNum: 30000, FPSDen: 1001}).FPS(); f < 29.9 || f > 30 { + t.Fatalf("%v", f) + } +} + +// A body cut short on the header request only is an error at the header, not +// something the second request papers over. +func TestFetchHeaderBodyCut(t *testing.T) { + b := y4mBytes(3) + var n atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n.Add(1) == 1 { + w.Header().Set("Content-Length", strconv.Itoa(len(b)+5000)) + w.Write(b[:30]) + return + } + w.Write(b) + })) + t.Cleanup(srv.Close) + d := filepath.Join(t.TempDir(), "p.y4m") + _, err := FetchPrefix(context.Background(), srv.Client(), srv.URL, 2, d) + if err == nil || !strings.Contains(err.Error(), "EOF") || n.Load() != 1 { + t.Fatalf("%v after %d requests", err, n.Load()) + } +} + +func TestFetchFileErrorsAreNamed(t *testing.T) { + srv := fetchServer(t, y4mBytes(3), 200, false) + ctx := context.Background() + base := t.TempDir() + f := filepath.Join(base, "f") + os.WriteFile(f, nil, 0o644) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, filepath.Join(f, "sub", "p.y4m")); err == nil || !strings.Contains(err.Error(), "mkdir") { + t.Fatalf("%v", err) + } + d := filepath.Join(base, "p.y4m") + os.MkdirAll(d+".part", 0o755) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, d); err == nil || !strings.Contains(err.Error(), ".part") { + t.Fatalf("%v", err) + } +} + +func TestExecuteErrorsAreNamed(t *testing.T) { + ctx := context.Background() + mk := func(t *testing.T) Config { return testConfig(t, &fakeExec{vtVer: vt}, 1) } + t.Run("work under a file", func(t *testing.T) { + cfg := mk(t) + f := filepath.Join(cfg.Work, "f") + os.WriteFile(f, nil, 0o644) + cfg.Work = filepath.Join(f, "sub") + if _, err := Execute(ctx, cfg); err == nil || strings.HasPrefix(err.Error(), "clip") || !strings.Contains(err.Error(), "mkdir") { + t.Fatalf("%v", err) + } + }) + t.Run("fetch status", func(t *testing.T) { + cfg := mk(t) + srv := fetchServer(t, y4mBytes(3), 404, false) + cfg.Clips[0].URL = srv.URL + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "HTTP 404") { + t.Fatalf("%v", err) + } + }) + t.Run("png dir is a file", func(t *testing.T) { + cfg := mk(t) + p := filepath.Join(cfg.Work, "c1", "png") + os.MkdirAll(filepath.Dir(p), 0o755) + os.WriteFile(p, nil, 0o644) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "mkdir") { + t.Fatalf("%v", err) + } + }) + t.Run("svg dir is a file", func(t *testing.T) { + cfg := mk(t) + p := filepath.Join(cfg.Work, "c1", "svg_01_3") + os.MkdirAll(filepath.Dir(p), 0o755) + os.WriteFile(p, nil, 0o644) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "mkdir") { + t.Fatalf("%v", err) + } + }) + t.Run("prefix is a directory", func(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("directory reads fail differently") + } + cfg := mk(t) + os.MkdirAll(filepath.Join(cfg.Work, "c1", "prefix.y4m"), 0o755) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "directory") { + t.Fatalf("%v", err) + } + }) +} diff --git a/internal/bench/edge_test.go b/internal/bench/edge_test.go new file mode 100644 index 0000000..e0d57d5 --- /dev/null +++ b/internal/bench/edge_test.go @@ -0,0 +1,313 @@ +package bench + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestIoUDisjoint(t *testing.T) { + a := Path{X0: 0, Y0: 0, X1: 10, Y1: 10} + for name, b := range map[string]Path{ + "x only": {X0: 20, Y0: 0, X1: 30, Y1: 10}, + "y only": {X0: 0, Y0: 20, X1: 10, Y1: 30}, + "both": {X0: 20, Y0: 20, X1: 30, Y1: 30}, + } { + if v := IoU(a, b); v != 0 { + t.Errorf("%s: %v", name, v) + } + if v := IoU(b, a); v != 0 { + t.Errorf("%s reversed: %v", name, v) + } + } +} + +func TestSummariseEmpty(t *testing.T) { + s := Summarise(nil) + if s.Pairs != 0 || s.Churn != 0 || s.MeanShift != 0 || s.AreaUnmatched != 0 { + t.Fatalf("%+v", s) + } +} + +func TestMatchedEqualQuality(t *testing.T) { + m := MatchedBytes([]RDPoint{{Bytes: 5, Q: 30}, {Bytes: 9, Q: 30}}, 30) + if m.Bytes != 9 || m.Kind != MatchEstimated { + t.Fatalf("%+v", m) + } +} + +func TestParseRefusalsAreJSONErrors(t *testing.T) { + _, err := ParseResults([]byte("{")) + if err == nil || strings.Contains(err.Error(), "schema") || strings.Contains(err.Error(), "no runs") { + t.Fatalf("%v", err) + } + _, err = ParseManifest([]byte("{")) + if err == nil || strings.Contains(err.Error(), "empty") { + t.Fatalf("%v", err) + } + _, err = ParseToolPins([]byte("{")) + if err == nil || !strings.Contains(err.Error(), "tools pins") { + t.Fatalf("%v", err) + } + if ps, err := ParseToolPins([]byte(`[{"name":"a","version":"1","source":"s"}]`)); err != nil || len(ps) != 1 { + t.Fatalf("%v %v", ps, err) + } +} + +func TestRenderOmitsEmptySections(t *testing.T) { + r := &Results{Schema: SchemaVersion, Frames: 3, Tools: map[string]string{}, + Runs: []Run{{Clip: "c", Class: "screen", Variant: "x264 crf23", Family: "x264", Frames: 3, Bytes: 90, PSNR: 30, VMAF: 60}}} + var buf bytes.Buffer + if err := Render(&buf, r); err != nil { + t.Fatal(err) + } + s := buf.String() + if strings.Contains(s, "Matched VMAF") || strings.Contains(s, "Summary by content class") { + t.Fatalf("empty sections printed:\n%s", s) + } +} + +func TestLoadFor(t *testing.T) { + read := func(b string, err error) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + if p != "/proc/loadavg" { + t.Errorf("path %s", p) + } + return []byte(b), err + } + } + sysctl := func(b string, err error) func() ([]byte, error) { + return func() ([]byte, error) { return []byte(b), err } + } + no := errors.New("no") + if v, err := loadFor("linux", read("1.25 2 3 1/2 4\n", nil), nil); err != nil || v != 1.25 { + t.Fatalf("%v %v", v, err) + } + if _, err := loadFor("linux", read("", no), nil); err != no { + t.Fatalf("%v", err) + } + if _, err := loadFor("linux", read("garbage", nil), nil); err == nil { + t.Fatal("garbage accepted") + } + for _, os := range []string{"darwin", "freebsd", "netbsd", "openbsd"} { + if v, err := loadFor(os, nil, sysctl("{ 3.50 2.00 1.00 }\n", nil)); err != nil || v != 3.5 { + t.Fatalf("%s: %v %v", os, v, err) + } + if _, err := loadFor(os, nil, sysctl("", no)); err != no { + t.Fatalf("%s: %v", os, err) + } + if _, err := loadFor(os, nil, sysctl("junk", nil)); err == nil { + t.Fatalf("%s: junk accepted", os) + } + } + if _, err := loadFor("plan9", nil, nil); err == nil || !strings.Contains(err.Error(), "plan9") { + t.Fatalf("%v", err) + } + if _, err := SystemLoad(); err != nil { + t.Log("SystemLoad on this host:", err) + } +} + +func TestSVGLimits(t *testing.T) { + oldB, oldP := svgBytesLimit, svgPathsLimit + t.Cleanup(func() { svgBytesLimit, svgPathsLimit = oldB, oldP }) + svg := []byte(``) + svgPathsLimit = 1 + if _, err := ParsePaths(svg); err == nil || !strings.Contains(err.Error(), "paths") { + t.Fatalf("%v", err) + } + svgPathsLimit = 2 + if ps, err := ParsePaths(svg); err != nil || len(ps) != 2 { + t.Fatalf("%v %v", ps, err) + } + svgBytesLimit = len(svg) - 1 + if _, err := ParsePaths(svg); err == nil || !strings.Contains(err.Error(), "larger") { + t.Fatalf("%v", err) + } + svgBytesLimit = len(svg) + if _, err := ParsePaths(svg); err != nil { + t.Fatalf("%v", err) + } +} + +func TestSVGAttrAndColour(t *testing.T) { + // an unterminated quote is no value + if v, ok := attr(`d="M0 0`, "d"); ok { + t.Fatalf("%q", v) + } + if v, ok := attr(`xd="1" d="2"`, "d"); !ok || v != "2" { + t.Fatalf("%q %v", v, ok) + } + if v, ok := attr(`d=""`, "d"); !ok || v != "" { + t.Fatalf("%q %v", v, ok) + } + for _, s := range []string{"#12345", "#1234567", "#12345g", "", "#"} { + if r, g, b := parseHexColor(s); r|g|b != 0 { + t.Errorf("%q gave %d %d %d", s, r, g, b) + } + } + if r, g, b := parseHexColor("#102030"); r != 0x10 || g != 0x20 || b != 0x30 { + t.Errorf("%d %d %d", r, g, b) + } + if r, g, b := parseHexColor("#abc"); r != 0xaa || g != 0xbb || b != 0xcc { + t.Errorf("%d %d %d", r, g, b) + } + // numbers that are only signs, dots or exponents are refused + for _, s := range []string{"-", ".", "+.", "e5", "-e5"} { + if _, _, ok := scanNumber(s, 0); ok { + t.Errorf("%q accepted", s) + } + } + if v, i, ok := scanNumber("1e", 0); !ok || v != 1 || i != 1 { + t.Errorf("1e: %v %d %v", v, i, ok) + } + if v, i, ok := scanNumber("2.5e+1x", 0); !ok || v != 25 || i != 6 { + t.Errorf("2.5e+1: %v %d %v", v, i, ok) + } +} + +// fetchServer serves b whatever the request, with the given status. +func fetchServer(t *testing.T, b []byte, status int, short bool) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if short { + w.Header().Set("Content-Length", strconv.Itoa(len(b)+1000)) + } + w.WriteHeader(status) + w.Write(b) + })) + t.Cleanup(srv.Close) + return srv +} + +func y4mBytes(frames int) []byte { + b := []byte("YUV4MPEG2 W4 H2 F1:1 C420\n") + for i := 0; i < frames; i++ { + b = append(b, "FRAME\n"...) + b = append(b, make([]byte, 12)...) + } + return b +} + +func TestFetchPrefixEveryFailure(t *testing.T) { + ctx := context.Background() + dest := func(t *testing.T) string { return filepath.Join(t.TempDir(), "d", "p.y4m") } + + t.Run("bad URL", func(t *testing.T) { + if _, err := FetchPrefix(ctx, nil, "http://[::1", 2, dest(t)); err == nil { + t.Fatal("accepted") + } + }) + t.Run("nil client, closed server", func(t *testing.T) { + srv := fetchServer(t, nil, 200, false) + srv.Close() + if _, err := FetchPrefix(ctx, nil, srv.URL, 2, dest(t)); err == nil { + t.Fatal("accepted") + } + }) + t.Run("404 with a valid body", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(3), 404, false) + _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, dest(t)) + if err == nil || !strings.Contains(err.Error(), "HTTP 404") || !strings.Contains(err.Error(), srv.URL) { + t.Fatalf("%v", err) + } + }) + t.Run("200 and 206 are accepted", func(t *testing.T) { + for _, st := range []int{200, 206} { + srv := fetchServer(t, y4mBytes(3), st, false) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, dest(t)); err != nil { + t.Fatalf("%d: %v", st, err) + } + } + }) + t.Run("garbage header names the URL", func(t *testing.T) { + srv := fetchServer(t, []byte("not a y4m file\n"), 200, false) + _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, dest(t)) + if err == nil || !strings.Contains(err.Error(), srv.URL) { + t.Fatalf("%v", err) + } + }) + t.Run("absurd prefix", func(t *testing.T) { + srv := fetchServer(t, []byte("YUV4MPEG2 W16384 H16384 F1:1 C444p16\n"), 200, false) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 1<<30, dest(t)); err == nil { + t.Fatal("accepted") + } + }) + t.Run("second request fails", func(t *testing.T) { + var n atomic.Int32 + b := y4mBytes(3) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n.Add(1) > 1 { + http.Error(w, "no", 500) + return + } + w.Write(b) + })) + t.Cleanup(srv.Close) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, dest(t)); err == nil || !strings.Contains(err.Error(), "500") { + t.Fatalf("%v", err) + } + }) + t.Run("short body", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(1), 200, true) + d := dest(t) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, d); err == nil { + t.Fatal("accepted") + } + if fileExists(d) || fileExists(d+".part") { + t.Fatal("a cut download was left behind") + } + }) + t.Run("short but complete prefix of a longer file", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(1), 200, false) + d := dest(t) + _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, d) + if err == nil || !strings.Contains(err.Error(), "of") { + t.Fatalf("%v", err) + } + if fileExists(d) { + t.Fatal("kept") + } + }) + t.Run("directory under a file", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(3), 200, false) + base := t.TempDir() + f := filepath.Join(base, "f") + os.WriteFile(f, nil, 0o644) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, filepath.Join(f, "sub", "p.y4m")); err == nil { + t.Fatal("accepted") + } + }) + t.Run("part is a directory", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(3), 200, false) + d := dest(t) + os.MkdirAll(d+".part", 0o755) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, d); err == nil { + t.Fatal("accepted") + } + }) + t.Run("dest is a non-empty directory", func(t *testing.T) { + srv := fetchServer(t, y4mBytes(3), 200, false) + d := dest(t) + os.MkdirAll(filepath.Join(d, "x"), 0o755) + if _, err := FetchPrefix(ctx, srv.Client(), srv.URL, 2, d); err == nil { + t.Fatal("accepted") + } + }) +} + +func TestNoClockSkewInTestConfig(t *testing.T) { + // guards the helper the other tests rely on + if testConfig(t, &fakeExec{}, 0).Now().Before(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)) { + t.Fatal("clock") + } +} diff --git a/internal/bench/exec.go b/internal/bench/exec.go new file mode 100644 index 0000000..032d35d --- /dev/null +++ b/internal/bench/exec.go @@ -0,0 +1,69 @@ +package bench + +import ( + "bytes" + "context" + "fmt" + "os/exec" + "strings" + "time" +) + +// ExecResult is what running a program produced: its combined output (the +// last 256 KiB of it) and what it cost. +type ExecResult struct { + Out string + Wall time.Duration + CPU time.Duration // user plus system time of the process +} + +// Executor runs programs. The real one is OSExec; tests substitute a fake, so +// the orchestration is tested without ffmpeg. +type Executor interface { + Run(ctx context.Context, name string, args ...string) (ExecResult, error) +} + +// OSExec runs real processes with stdin closed. +type OSExec struct{} + +const tailLimit = 256 << 10 + +// tail keeps the last tailLimit bytes written to it. +type tail struct{ buf []byte } + +func (t *tail) Write(p []byte) (int, error) { + t.buf = append(t.buf, p...) + if len(t.buf) > 2*tailLimit { + t.buf = append([]byte(nil), t.buf[len(t.buf)-tailLimit:]...) + } + return len(p), nil +} + +func (t *tail) String() string { + if len(t.buf) > tailLimit { + return string(t.buf[len(t.buf)-tailLimit:]) + } + return string(t.buf) +} + +// Run implements Executor. +func (OSExec) Run(ctx context.Context, name string, args ...string) (ExecResult, error) { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Stdin = nil + var t tail + cmd.Stdout, cmd.Stderr = &t, &t + start := time.Now() + err := cmd.Run() + res := ExecResult{Out: t.String(), Wall: time.Since(start)} + if cmd.ProcessState != nil { + res.CPU = cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime() + } + if err != nil { + msg := res.Out + if len(msg) > 1500 { + msg = msg[len(msg)-1500:] + } + return res, fmt.Errorf("%s %s: %w\n%s", name, strings.Join(args, " "), err, bytes.TrimSpace([]byte(msg))) + } + return res, nil +} diff --git a/internal/bench/fetch.go b/internal/bench/fetch.go new file mode 100644 index 0000000..964d6a5 --- /dev/null +++ b/internal/bench/fetch.go @@ -0,0 +1,101 @@ +package bench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" +) + +// FetchPrefix downloads the header and the first n frames of the y4m file at +// url into dest and returns the SHA-256 of exactly those bytes. Only the prefix +// is requested (an HTTP Range request); a server that ignores Range sends the +// whole file, of which only the prefix is read and kept. The file is written +// under a temporary name and renamed once complete, so a cut download never +// leaves a prefix that looks whole. +func FetchPrefix(ctx context.Context, client *http.Client, url string, n int, dest string) (string, error) { + head, err := get(ctx, client, url, 0, MaxHeaderLen-1) + if err != nil { + return "", err + } + hdr, err := io.ReadAll(io.LimitReader(head, MaxHeaderLen)) + head.Close() + if err != nil { + return "", err + } + y, err := ParseY4MHeader(hdr) + if err != nil { + return "", fmt.Errorf("%s: %w", url, err) + } + want, err := y.PrefixLen(n) + if err != nil { + return "", err + } + body, err := get(ctx, client, url, 0, want-1) + if err != nil { + return "", err + } + defer body.Close() + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return "", err + } + tmp := dest + ".part" + f, err := os.Create(tmp) + if err != nil { + return "", err + } + h := sha256.New() + got, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, want)) + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil && got != want { + err = fmt.Errorf("%s: got %d of %d bytes", url, got, want) + } + if err != nil { + os.Remove(tmp) + return "", err + } + if err := os.Rename(tmp, dest); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +// get requests bytes first..last. A 200 reply is accepted (the caller limits +// the read); anything but 200 and 206 is an error. +func get(ctx context.Context, client *http.Client, url string, first, last int64) (io.ReadCloser, error) { + if client == nil { + client = http.DefaultClient + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", first, last)) + resp, err := client.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { + resp.Body.Close() + return nil, fmt.Errorf("%s: HTTP %s", url, resp.Status) + } + return resp.Body, nil +} + +// VerifyPin compares a computed SHA-256 with the pinned one. +func VerifyPin(name, got, pinned string) error { + if pinned == "" { + return fmt.Errorf("clip %s has no pinned SHA-256 (computed %s); run `vectorbench pin`, read what it fetched, and commit the result", name, got) + } + if got != pinned { + return errors.New("clip " + name + ": SHA-256 mismatch: pinned " + pinned + ", got " + got) + } + return nil +} diff --git a/internal/bench/interp.go b/internal/bench/interp.go new file mode 100644 index 0000000..668caeb --- /dev/null +++ b/internal/bench/interp.go @@ -0,0 +1,71 @@ +package bench + +import ( + "math" + "sort" +) + +// RDPoint is one measured rate-quality point of a codec: its size and the +// quality (PSNR in dB or VMAF) it reached. +type RDPoint struct { + Label string + Bytes int64 + Q float64 +} + +// MatchKind says how a matched size was obtained. It is what the report +// prints next to the number, so a reader can tell a measurement from an +// estimate. +type MatchKind string + +const ( + // MatchEstimated: log-linear interpolation between the two measured points + // that bracket the target quality. + MatchEstimated MatchKind = "est." + // MatchUpperBound: the codec's cheapest measured setting is already better + // than the target, so the matched size is at most this one. + MatchUpperBound MatchKind = "<=" + // MatchUnreachable: no measured setting of the codec reaches the target. + MatchUnreachable MatchKind = "n/a" +) + +// Matched is a codec size at a target quality. +type Matched struct { + Bytes float64 + Kind MatchKind +} + +// MatchedBytes gives the size a codec needs for quality q, by interpolating +// log(bytes) linearly in quality between the two measured points around q. +// Points at or above the lossless sentinel are ignored. +func MatchedBytes(points []RDPoint, q float64) Matched { + var ps []RDPoint + for _, p := range points { + if p.Bytes > 0 && p.Q < PSNRInf-1 && !math.IsNaN(p.Q) { + ps = append(ps, p) + } + } + if len(ps) == 0 { + return Matched{Kind: MatchUnreachable} + } + sort.SliceStable(ps, func(i, j int) bool { return ps[i].Q < ps[j].Q }) + if q < ps[0].Q { + return Matched{Bytes: float64(ps[0].Bytes), Kind: MatchUpperBound} + } + last := ps[len(ps)-1] + if q > last.Q { + return Matched{Kind: MatchUnreachable} + } + for i := 1; i < len(ps); i++ { + a, b := ps[i-1], ps[i] + if q <= b.Q { + if b.Q == a.Q { + return Matched{Bytes: float64(b.Bytes), Kind: MatchEstimated} + } + t := (q - a.Q) / (b.Q - a.Q) + lb := math.Log(float64(a.Bytes)) + t*(math.Log(float64(b.Bytes))-math.Log(float64(a.Bytes))) + return Matched{Bytes: math.Exp(lb), Kind: MatchEstimated} + } + } + return Matched{Bytes: float64(last.Bytes), Kind: MatchEstimated} +} diff --git a/internal/bench/interp_test.go b/internal/bench/interp_test.go new file mode 100644 index 0000000..854b245 --- /dev/null +++ b/internal/bench/interp_test.go @@ -0,0 +1,43 @@ +package bench + +import ( + "math" + "testing" +) + +func TestMatchedBytes(t *testing.T) { + pts := []RDPoint{{"a", 1000, 90}, {"b", 100, 50}, {"c", 10000, 99}, {"lossless", 99999, PSNRInf}} + // Midway in quality between (50,100) and (90,1000): geometric mean of the sizes. + m := MatchedBytes(pts, 70) + if m.Kind != MatchEstimated || math.Abs(m.Bytes-math.Sqrt(100*1000)) > 1e-6 { + t.Fatalf("%+v", m) + } + if m := MatchedBytes(pts, 90); m.Kind != MatchEstimated || math.Abs(m.Bytes-1000) > 1e-6 { + t.Fatalf("on a point: %+v", m) + } + if m := MatchedBytes(pts, 20); m.Kind != MatchUpperBound || m.Bytes != 100 { + t.Fatalf("below the range: %+v", m) + } + if m := MatchedBytes(pts, 99.5); m.Kind != MatchUnreachable { + t.Fatalf("above the range: %+v", m) + } + if m := MatchedBytes(nil, 50); m.Kind != MatchUnreachable { + t.Fatalf("no points: %+v", m) + } + if m := MatchedBytes([]RDPoint{{"x", 5, 40}, {"y", 9, 40}}, 40); m.Kind != MatchEstimated { + t.Fatalf("equal quality: %+v", m) + } + if m := MatchedBytes([]RDPoint{{"x", 5, 40}}, 40); m.Kind != MatchEstimated || m.Bytes != 5 { + t.Fatalf("single point: %+v", m) + } +} + +func FuzzMatchedBytes(f *testing.F) { + f.Add(10.0, 100.0, 20.0, 400.0, 15.0) + f.Fuzz(func(t *testing.T, q1, b1, q2, b2, q float64) { + m := MatchedBytes([]RDPoint{{"a", int64(b1), q1}, {"b", int64(b2), q2}}, q) + if m.Kind == MatchEstimated && (math.IsNaN(m.Bytes) || m.Bytes < 0) { + t.Fatalf("%+v", m) + } + }) +} diff --git a/internal/bench/load.go b/internal/bench/load.go new file mode 100644 index 0000000..bcd293c --- /dev/null +++ b/internal/bench/load.go @@ -0,0 +1,36 @@ +package bench + +import ( + "errors" + "os" + "os/exec" + "runtime" +) + +// SystemLoad reads the one-minute load average: /proc/loadavg on Linux, +// `sysctl -n vm.loadavg` on macOS and the BSDs. Elsewhere it is an error, and a +// run then needs an explicit load waiver. +func SystemLoad() (float64, error) { + return loadFor(runtime.GOOS, os.ReadFile, func() ([]byte, error) { + return exec.Command("sysctl", "-n", "vm.loadavg").Output() + }) +} + +// loadFor is SystemLoad with the operating system and its two sources passed in. +func loadFor(goos string, readFile func(string) ([]byte, error), sysctl func() ([]byte, error)) (float64, error) { + switch goos { + case "linux": + b, err := readFile("/proc/loadavg") + if err != nil { + return 0, err + } + return ParseProcLoadavg(string(b)) + case "darwin", "freebsd", "netbsd", "openbsd": + out, err := sysctl() + if err != nil { + return 0, err + } + return ParseSysctlLoadavg(string(out)) + } + return 0, errors.New("no load average source on " + goos) +} diff --git a/internal/bench/manifest.go b/internal/bench/manifest.go new file mode 100644 index 0000000..c76717c --- /dev/null +++ b/internal/bench/manifest.go @@ -0,0 +1,86 @@ +package bench + +import ( + _ "embed" + "encoding/json" + "errors" + "fmt" + "strings" +) + +// PinFrames is the number of frames whose SHA-256 the manifest pins. A run +// uses the first n <= PinFrames of them. +const PinFrames = 24 + +//go:embed clips.json +var clipsJSON []byte + +//go:embed tools.json +var toolsJSON []byte + +// Clip is one test sequence, fetched from Xiph by URL, never committed. +type Clip struct { + Name string `json:"name"` + Class string `json:"class"` // cartoon, anime, screen, natural + Desc string `json:"desc"` + URL string `json:"url"` + FPS float64 `json:"fps"` + SHA256 string `json:"sha256"` // of the header and the first PinFrames frames +} + +// ToolPin is the version a tool must report. Only the tools whose output is +// the subject of the comparison are pinned (VTracer, resvg); the encoders and +// ffmpeg differ by platform and are recorded in every result instead. +type ToolPin struct { + Name string `json:"name"` + Version string `json:"version"` // substring of the tool's version output + Source string `json:"source"` // how to get exactly this version +} + +// Manifest loads the embedded clip list. +func Manifest() ([]Clip, error) { + return ParseManifest(clipsJSON) +} + +// ParseManifest reads a clip list and refuses anything the downloader could +// misuse: duplicate names, names that are not plain file names, non-https URLs. +func ParseManifest(b []byte) ([]Clip, error) { + var cs []Clip + if err := json.Unmarshal(b, &cs); err != nil { + return nil, fmt.Errorf("clips manifest: %w", err) + } + seen := map[string]bool{} + for _, c := range cs { + if c.Name == "" || strings.ContainsAny(c.Name, `/\.`) || seen[c.Name] { + return nil, fmt.Errorf("clips manifest: bad or duplicate name %q", c.Name) + } + seen[c.Name] = true + if !strings.HasPrefix(c.URL, "https://") { + return nil, fmt.Errorf("clips manifest: %s: URL must be https", c.Name) + } + if c.FPS <= 0 { + return nil, fmt.Errorf("clips manifest: %s: no frame rate", c.Name) + } + switch c.Class { + case "cartoon", "anime", "screen", "natural": + default: + return nil, fmt.Errorf("clips manifest: %s: unknown class %q", c.Name, c.Class) + } + } + if len(cs) == 0 { + return nil, errors.New("clips manifest: empty") + } + return cs, nil +} + +// ToolPins loads the embedded tool pins. +func ToolPins() ([]ToolPin, error) { return ParseToolPins(toolsJSON) } + +// ParseToolPins reads a tool pin list. +func ParseToolPins(b []byte) ([]ToolPin, error) { + var ps []ToolPin + if err := json.Unmarshal(b, &ps); err != nil { + return nil, fmt.Errorf("tools pins: %w", err) + } + return ps, nil +} diff --git a/internal/bench/parse.go b/internal/bench/parse.go new file mode 100644 index 0000000..487a605 --- /dev/null +++ b/internal/bench/parse.go @@ -0,0 +1,82 @@ +package bench + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" +) + +var ( + rePSNR = regexp.MustCompile(`average:([0-9.]+|inf)`) + reVMAF = regexp.MustCompile(`VMAF score: ([0-9.]+)`) +) + +// PSNRInf stands for an infinite PSNR (identical frames) in the results. +const PSNRInf = 999 + +// ParsePSNR extracts the average PSNR from ffmpeg's psnr filter summary. +func ParsePSNR(log string) (float64, error) { + m := rePSNR.FindAllStringSubmatch(log, -1) + if len(m) == 0 { + return 0, errors.New("no PSNR summary in ffmpeg output") + } + v := m[len(m)-1][1] + if v == "inf" { + return PSNRInf, nil + } + return strconv.ParseFloat(v, 64) +} + +// ParseVMAF extracts the pooled VMAF score from ffmpeg's libvmaf output. +func ParseVMAF(log string) (float64, error) { + m := reVMAF.FindStringSubmatch(log) + if m == nil { + return 0, errors.New("no VMAF score in ffmpeg output") + } + return strconv.ParseFloat(m[1], 64) +} + +// ParseProcLoadavg reads the one-minute load from /proc/loadavg +// ("2.97 1.94 1.41 5/3246 629059"). +func ParseProcLoadavg(s string) (float64, error) { + f := strings.Fields(s) + if len(f) < 3 { + return 0, fmt.Errorf("loadavg: %q", s) + } + return parseLoad(f[0]) +} + +// ParseSysctlLoadavg reads the one-minute load from `sysctl -n vm.loadavg` +// ("{ 76.09 41.78 25.36 }"). +func ParseSysctlLoadavg(s string) (float64, error) { + f := strings.Fields(strings.Trim(strings.TrimSpace(s), "{}")) + if len(f) < 3 { + return 0, fmt.Errorf("loadavg: %q", s) + } + return parseLoad(f[0]) +} + +func parseLoad(s string) (float64, error) { + v, err := strconv.ParseFloat(s, 64) + if err != nil || v < 0 || v != v { + return 0, fmt.Errorf("loadavg: bad value %q", s) + } + return v, nil +} + +// ParseVersionLine returns the first non-empty line of a tool's version +// output, trimmed and cut to 200 bytes (a version line is data for a result +// file, not something to trust). +func ParseVersionLine(out string) string { + for _, l := range strings.Split(out, "\n") { + if l = strings.TrimSpace(l); l != "" { + if len(l) > 200 { + l = l[:200] + } + return l + } + } + return "" +} diff --git a/internal/bench/parse_test.go b/internal/bench/parse_test.go new file mode 100644 index 0000000..a6b491b --- /dev/null +++ b/internal/bench/parse_test.go @@ -0,0 +1,74 @@ +package bench + +import ( + "math" + "testing" +) + +func TestParsePSNR(t *testing.T) { + log := "[Parsed_psnr_2 @ 0x1] PSNR y:30 u:31 v:32 average:30.456 min:29 max:31\n" + if v, err := ParsePSNR(log); err != nil || v != 30.456 { + t.Fatalf("%v %v", v, err) + } + if v, _ := ParsePSNR("PSNR average:inf min:inf"); v != PSNRInf { + t.Fatalf("inf -> %v", v) + } + if _, err := ParsePSNR("nothing"); err == nil { + t.Fatal("no summary accepted") + } +} + +func TestParseVMAF(t *testing.T) { + if v, err := ParseVMAF("[libvmaf @ 0x1] VMAF score: 93.250000\n"); err != nil || v != 93.25 { + t.Fatalf("%v %v", v, err) + } + if _, err := ParseVMAF("VMAF score: x"); err == nil { + t.Fatal("garbage accepted") + } +} + +func FuzzParseQuality(f *testing.F) { + f.Add("PSNR average:30.1 VMAF score: 91.2") + f.Add("average:inf") + f.Fuzz(func(t *testing.T, s string) { + if v, err := ParsePSNR(s); err == nil && math.IsNaN(v) { + t.Fatal("NaN PSNR") + } + if v, err := ParseVMAF(s); err == nil && math.IsNaN(v) { + t.Fatal("NaN VMAF") + } + }) +} + +func TestLoadParsers(t *testing.T) { + if v, err := ParseProcLoadavg("2.97 1.94 1.41 5/3246 629059\n"); err != nil || v != 2.97 { + t.Fatalf("%v %v", v, err) + } + if v, err := ParseSysctlLoadavg("{ 76.09 41.78 25.36 }\n"); err != nil || v != 76.09 { + t.Fatalf("%v %v", v, err) + } + for _, s := range []string{"", "1,85 1,29 1,16", "-1 0 0", "NaN 0 0"} { + if _, err := ParseProcLoadavg(s); err == nil { + t.Errorf("proc accepted %q", s) + } + } + if _, err := ParseSysctlLoadavg("{ }"); err == nil { + t.Error("sysctl accepted an empty list") + } + if _, err := SystemLoad(); err != nil { + t.Skipf("no load source here: %v", err) + } +} + +func TestParseVersionLine(t *testing.T) { + if got := ParseVersionLine("\n visioncortex VTracer 0.6.5 \nmore"); got != "visioncortex VTracer 0.6.5" { + t.Fatal(got) + } + long := make([]byte, 500) + for i := range long { + long[i] = 'a' + } + if len(ParseVersionLine(string(long))) != 200 || ParseVersionLine("") != "" { + t.Fatal("limits") + } +} diff --git a/internal/bench/report.go b/internal/bench/report.go new file mode 100644 index 0000000..ce404fd --- /dev/null +++ b/internal/bench/report.go @@ -0,0 +1,204 @@ +package bench + +import ( + "fmt" + "io" + "math" + "sort" + "strings" +) + +var codecFamilies = []struct{ Family, Label string }{ + {"x264", "x264"}, {"x265", "x265"}, {"svtav1", "SVT-AV1"}, {"vp9", "VP9"}, +} + +// Render writes the Markdown report of a results file. Every number is marked +// as measured (read from a run) or estimated (interpolated between two +// measured points of a codec), and the header says on what machine, under what +// load and with which tool versions it was taken. +func Render(w io.Writer, r *Results) error { + var b strings.Builder + b.WriteString("# Vector video against codecs: results\n\n") + renderHeader(&b, r) + b.WriteString("How to read the tables. **measured**: the number comes from one run. ") + b.WriteString("**est.**: size a codec needs for the same quality, interpolated (log of the size, linear in quality) between the two measured settings that bracket it. ") + b.WriteString("**<=**: the codec's cheapest measured setting is already above the vector result's quality, so the codec needs at most that much (the ratio is then a lower bound, printed with `>=`). ") + b.WriteString("**n/a**: no measured setting of the codec reaches that quality. ") + b.WriteString("Sizes are per frame; the vector size is the SVG text, plain and gzip-compressed (a compressed codec stream does not shrink under gzip).\n\n") + + byClip := map[string][]Run{} + var order []string + for _, run := range r.Runs { + if _, ok := byClip[run.Clip]; !ok { + order = append(order, run.Clip) + } + byClip[run.Clip] = append(byClip[run.Clip], run) + } + info := map[string]ClipInfo{} + for _, c := range r.Clips { + info[c.Name] = c + } + classRatios := map[string][]float64{} + for _, name := range order { + runs := byClip[name] + ci := info[name] + fmt.Fprintf(&b, "## %s (%s", name, runs[0].Class) + if ci.Width > 0 { + fmt.Fprintf(&b, ", %dx%d", ci.Width, ci.Height) + } + fmt.Fprintf(&b, ", %d frames)\n\n", runs[0].Frames) + renderRuns(&b, runs, ci.FPS) + renderMatched(&b, runs, classRatios) + } + renderClassSummary(&b, classRatios) + _, err := io.WriteString(w, b.String()) + return err +} + +func renderHeader(b *strings.Builder, r *Results) { + m := r.Machine + fmt.Fprintf(b, "Run: %s to %s, vectorbench %s, %d frames per clip.\n\n", r.Started.Format("2006-01-02 15:04 MST"), r.Finished.Format("15:04 MST"), r.Tool, r.Frames) + fmt.Fprintf(b, "Machine: %s, %s/%s, %d CPUs, one-minute load %.2f at start and %.2f at end (limit %.1f).", m.Hostname, m.OS, m.Arch, m.CPUs, m.LoadStart, m.LoadEnd, m.MaxLoad) + if m.Note != "" { + fmt.Fprintf(b, " %s.", m.Note) + } + if m.LoadWaiver != "" { + fmt.Fprintf(b, " **Load waiver: %s. Treat the timings accordingly.**", m.LoadWaiver) + } + b.WriteString("\n\nTools:\n\n") + keys := make([]string, 0, len(r.Tools)) + for k := range r.Tools { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fmt.Fprintf(b, "- %s: `%s`\n", k, r.Tools[k]) + } + b.WriteString("\n") +} + +func renderRuns(b *strings.Builder, runs []Run, fps float64) { + b.WriteString("All rows are measured.\n\n") + b.WriteString("| variant | bytes/frame | kbit/s | gzip bytes/frame | PSNR dB | VMAF | encode s | vectorise s/frame | paths/frame | churn | unmatched area |\n") + b.WriteString("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n") + for _, r := range runs { + bpf := float64(r.Bytes) / float64(r.Frames) + kbit := "" + if fps > 0 { + kbit = fmt.Sprintf("%.0f", float64(r.Bytes)*8/1000/(float64(r.Frames)/fps)) + } + gz, enc, vec, paths, churn, area := "", "", "", "", "", "" + if r.Vector() { + gz = fmt.Sprintf("%.0f", float64(r.GzipBytes)/float64(r.Frames)) + vec = fmt.Sprintf("%.2f", r.VectoriseWallS/float64(r.Frames)) + paths = fmt.Sprintf("%.0f", r.PathsMean) + if r.Churn != nil { + churn = fmt.Sprintf("%.2f", r.Churn.Churn) + area = fmt.Sprintf("%.2f", r.Churn.AreaUnmatched) + } + } else if r.EncodeWallS > 0 { + enc = fmt.Sprintf("%.1f", r.EncodeWallS) + } + psnr := fmt.Sprintf("%.2f", r.PSNR) + if r.PSNR >= PSNRInf-1 { + psnr = "inf" + } + fmt.Fprintf(b, "| %s | %.0f | %s | %s | %s | %.1f | %s | %s | %s | %s | %s |\n", r.Variant, bpf, kbit, gz, psnr, r.VMAF, enc, vec, paths, churn, area) + } + b.WriteString("\n") +} + +// renderMatched prints, for each vector variant, what each codec needs for the +// same VMAF and the same PSNR. It appends the best-codec ratios to classRatios. +func renderMatched(b *strings.Builder, runs []Run, classRatios map[string][]float64) { + var vecs []Run + for _, r := range runs { + if r.Vector() { + vecs = append(vecs, r) + } + } + if len(vecs) == 0 { + return + } + for _, metric := range []string{"VMAF", "PSNR"} { + fmt.Fprintf(b, "Matched %s: bytes per frame a codec needs for the quality of each vectorisation (codec columns are est. / <= / n/a, vector columns are measured).\n\n", metric) + b.WriteString("| vectorisation | quality | vector bytes/frame | gzip bytes/frame | x264 | x265 | SVT-AV1 | VP9 | vector / best codec | gzip vector / best codec |\n") + b.WriteString("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n") + for _, v := range vecs { + q := v.VMAF + if metric == "PSNR" { + q = v.PSNR + } + n := float64(v.Frames) + vb, gb := float64(v.Bytes)/n, float64(v.GzipBytes)/n + var cells []string + best := Matched{Kind: MatchUnreachable} + for _, cf := range codecFamilies { + var rd []RDPoint + for _, r := range runs { + if r.Family != cf.Family { + continue + } + rq := r.VMAF + if metric == "PSNR" { + rq = r.PSNR + } + rd = append(rd, RDPoint{Label: r.Variant, Bytes: r.Bytes, Q: rq}) + } + m := MatchedBytes(rd, q) + cells = append(cells, fmtMatched(m, n)) + if m.Kind != MatchUnreachable && (best.Kind == MatchUnreachable || m.Bytes < best.Bytes) { + best = m + } + } + ratio, gratio := "n/a", "n/a" + if best.Kind != MatchUnreachable && best.Bytes > 0 { + prefix := "~" + if best.Kind == MatchUpperBound { + prefix = ">=" + } + ratio = fmt.Sprintf("%s%.0fx", prefix, vb*n/best.Bytes) + gratio = fmt.Sprintf("%s%.0fx", prefix, gb*n/best.Bytes) + if metric == "VMAF" { + classRatios[v.Class] = append(classRatios[v.Class], vb*n/best.Bytes) + } + } + fmt.Fprintf(b, "| %s | %.2f | %.0f | %.0f | %s | %s |\n", v.Variant, q, vb, gb, strings.Join(cells, " | "), ratio+" | "+gratio) + } + b.WriteString("\n") + } +} + +func fmtMatched(m Matched, frames float64) string { + switch m.Kind { + case MatchEstimated: + return fmt.Sprintf("%.0f (est.)", m.Bytes/frames) + case MatchUpperBound: + return fmt.Sprintf("<= %.0f", m.Bytes/frames) + } + return "n/a" +} + +func renderClassSummary(b *strings.Builder, classRatios map[string][]float64) { + if len(classRatios) == 0 { + return + } + b.WriteString("## Summary by content class\n\n") + b.WriteString("Size of the vectorisation divided by the size of the best codec at the same VMAF (plain SVG; estimated or lower-bound ratios, see the tables above), over every clip and VTracer variant of the class: smallest, median, largest.\n\n") + b.WriteString("| class | comparisons | smallest | median | largest |\n|---|---:|---:|---:|---:|\n") + classes := make([]string, 0, len(classRatios)) + for c := range classRatios { + classes = append(classes, c) + } + sort.Strings(classes) + for _, c := range classes { + v := append([]float64(nil), classRatios[c]...) + sort.Float64s(v) + med := v[len(v)/2] + if len(v)%2 == 0 { + med = (v[len(v)/2-1] + v[len(v)/2]) / 2 + } + fmt.Fprintf(b, "| %s | %d | %.0fx | %.0fx | %.0fx |\n", c, len(v), math.Round(v[0]), math.Round(med), math.Round(v[len(v)-1])) + } + b.WriteString("\n") +} diff --git a/internal/bench/report_test.go b/internal/bench/report_test.go new file mode 100644 index 0000000..66486bc --- /dev/null +++ b/internal/bench/report_test.go @@ -0,0 +1,111 @@ +package bench + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + "time" +) + +func sampleResults() *Results { + run := func(v, fam string, bytes int64, psnr, vmaf float64) Run { + return Run{Clip: "c1", Class: "screen", Variant: v, Family: fam, Frames: 3, Bytes: bytes, PSNR: psnr, VMAF: vmaf, Load1: 1} + } + enc := run("x264 crf23", "x264", 1000, 40, 90) + enc.EncodeWallS = 1.5 + hi := run("x264 crf40", "x264", 100, 30, 50) + vec := run("vtracer default", "vtracer", 500, 35, 70) + vec.VectoriseWallS = 30 + vec.PathsMean = 100 + vec.Churn = &ChurnSummary{Pairs: 2, Churn: 0.25} + return &Results{ + Schema: SchemaVersion, Tool: "vtest", Frames: 3, Started: time.Unix(0, 0), Finished: time.Unix(60, 0), + Machine: Machine{Hostname: "fractal", OS: "linux", Arch: "amd64", CPUs: 32, LoadStart: 2, LoadEnd: 2, MaxLoad: 8, Note: "taskset -c 9"}, + Tools: map[string]string{"vtracer": "visioncortex VTracer 0.6.5"}, + Clips: []ClipInfo{{Name: "c1", Class: "screen", Width: 4, Height: 2, FPS: 30}}, + Runs: []Run{run("png", "png", 5000, PSNRInf, 100), enc, hi, vec}, + } +} + +func TestRender(t *testing.T) { + var b bytes.Buffer + if err := Render(&b, sampleResults()); err != nil { + t.Fatal(err) + } + out := b.String() + for _, want := range []string{"fractal", "taskset -c 9", "VTracer 0.6.5", "c1", "screen", "vtracer default", "x264 crf23", "est.", "0.25"} { + if !strings.Contains(out, want) { + t.Errorf("report lacks %q:\n%s", want, out) + } + } + if !strings.Contains(out, "estimated") && !strings.Contains(out, "interpolat") { + t.Error("report does not say what is estimated") + } +} + +func TestParseResults(t *testing.T) { + js, _ := json.Marshal(sampleResults()) + if _, err := ParseResults(js); err != nil { + t.Fatal(err) + } + bad := sampleResults() + bad.Schema = 99 + js, _ = json.Marshal(bad) + if _, err := ParseResults(js); err == nil { + t.Error("wrong schema accepted") + } + bad = sampleResults() + bad.Runs = nil + js, _ = json.Marshal(bad) + if _, err := ParseResults(js); err == nil { + t.Error("no runs accepted") + } + bad = sampleResults() + bad.Runs[0].Frames = 0 + js, _ = json.Marshal(bad) + if _, err := ParseResults(js); err == nil { + t.Error("zero frames accepted") + } + if _, err := ParseResults([]byte("{")); err == nil { + t.Error("garbage accepted") + } +} + +func TestEmbeddedManifests(t *testing.T) { + clips, err := Manifest() + if err != nil { + t.Fatal(err) + } + classes := map[string]bool{} + for _, c := range clips { + classes[c.Class] = true + if !strings.HasPrefix(c.URL, "https://") { + t.Errorf("%s: %s", c.Name, c.URL) + } + } + for _, want := range []string{"natural", "screen", "cartoon", "anime"} { + if !classes[want] { + t.Errorf("no %s clip", want) + } + } + pins, err := ToolPins() + if err != nil || len(pins) < 2 { + t.Fatalf("%v %v", err, pins) + } +} + +func TestParseManifestRefusals(t *testing.T) { + for _, s := range []string{ + `[]`, `{`, + `[{"name":"","class":"screen","url":"https://x/a.y4m","fps":30}]`, + `[{"name":"a","class":"screen","url":"http://x/a.y4m","fps":30}]`, + `[{"name":"a","class":"screen","url":"https://x/a.y4m","fps":0}]`, + `[{"name":"a","class":"","url":"https://x/a.y4m","fps":30}]`, + `[{"name":"a/b","class":"screen","url":"https://x/a.y4m","fps":30}]`, + } { + if _, err := ParseManifest([]byte(s)); err == nil { + t.Errorf("accepted %s", s) + } + } +} diff --git a/internal/bench/results.go b/internal/bench/results.go new file mode 100644 index 0000000..cceb3ca --- /dev/null +++ b/internal/bench/results.go @@ -0,0 +1,103 @@ +package bench + +import ( + "encoding/json" + "errors" + "fmt" + "time" +) + +// SchemaVersion is bumped when the results JSON changes shape. +const SchemaVersion = 1 + +// Results is the file a run writes: what was measured, with what, on what. +type Results struct { + Schema int `json:"schema"` + Tool string `json:"vectorbench"` // version of this program + Started time.Time `json:"started"` + Finished time.Time `json:"finished"` + Frames int `json:"frames"` + Machine Machine `json:"machine"` + Tools map[string]string `json:"tool_versions"` + Clips []ClipInfo `json:"clips"` + Runs []Run `json:"runs"` +} + +// Machine says where the timings were taken. LoadStart and LoadEnd are the +// one-minute load average before the first and after the last measurement +// (-1 when unreadable); LoadWaiver is non-empty when the run was started above +// the load limit on purpose. +type Machine struct { + Hostname string `json:"hostname"` + OS string `json:"os"` + Arch string `json:"arch"` + CPUs int `json:"cpus"` + LoadStart float64 `json:"load1_start"` + LoadEnd float64 `json:"load1_end"` + MaxLoad float64 `json:"max_load"` + LoadWaiver string `json:"load_waiver,omitempty"` + Note string `json:"note,omitempty"` // e.g. "taskset -c 9, VPN open" +} + +// ClipInfo records what was actually fetched. +type ClipInfo struct { + Name string `json:"name"` + Class string `json:"class"` + URL string `json:"url"` + SHA256 string `json:"sha256"` + Width int `json:"width"` + Height int `json:"height"` + FPS float64 `json:"fps"` +} + +// Run is one variant (an encoder setting or a VTracer preset) on one clip. +type Run struct { + Clip string `json:"clip"` + Class string `json:"class"` + Variant string `json:"variant"` + Family string `json:"family"` // x264, x265, svtav1, vp9, vtracer, png + Frames int `json:"frames"` + + Load1 float64 `json:"load1"` // one-minute load when the run started, -1 unknown + + Bytes int64 `json:"bytes"` + GzipBytes int64 `json:"gzip_bytes,omitempty"` // vector variants only + PSNR float64 `json:"psnr_db"` + VMAF float64 `json:"vmaf"` + + // Seconds. Encode* is the encoder process, Vectorise* the sum over the + // frames of the VTracer process. Wall is elapsed time, CPU is user plus + // system time of the process. + EncodeWallS float64 `json:"encode_wall_s,omitempty"` + EncodeCPUS float64 `json:"encode_cpu_s,omitempty"` + VectoriseWallS float64 `json:"vectorise_wall_s,omitempty"` + VectoriseCPUS float64 `json:"vectorise_cpu_s,omitempty"` + + PathsMin int `json:"paths_min,omitempty"` + PathsMean float64 `json:"paths_mean,omitempty"` + PathsMax int `json:"paths_max,omitempty"` + Churn *ChurnSummary `json:"churn,omitempty"` +} + +// Vector reports whether the run is a vectorisation. +func (r Run) Vector() bool { return r.Family == "vtracer" } + +// ParseResults reads a results file and checks its schema. +func ParseResults(b []byte) (*Results, error) { + var r Results + if err := json.Unmarshal(b, &r); err != nil { + return nil, fmt.Errorf("results: %w", err) + } + if r.Schema != SchemaVersion { + return nil, fmt.Errorf("results: schema %d, this program reads %d", r.Schema, SchemaVersion) + } + if len(r.Runs) == 0 { + return nil, errors.New("results: no runs") + } + for _, run := range r.Runs { + if run.Frames <= 0 { + return nil, fmt.Errorf("results: run %s/%s has no frames", run.Clip, run.Variant) + } + } + return &r, nil +} diff --git a/internal/bench/runner.go b/internal/bench/runner.go new file mode 100644 index 0000000..f996f07 --- /dev/null +++ b/internal/bench/runner.go @@ -0,0 +1,387 @@ +package bench + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +// Config is everything a run needs. Tests fill Exec, Fetch and Load with fakes. +type Config struct { + Work string // durable working directory (clips, frames, encodes, cache) + Frames int // frames per clip, 1..PinFrames + Clips []Clip + Only []string // clip names to keep; empty = all + Variant []Variant + Jobs int // parallel VTracer processes; 1 keeps the timings honest + + FFmpeg, VTracer, Resvg string + + MaxLoad float64 // refuse to start above this one-minute load + LoadWaiver string // why a run above MaxLoad goes ahead anyway + AllowUnpinned bool // accept VTracer or resvg versions other than the pinned ones + Note string + + Version string + Log io.Writer + Exec Executor + Client *http.Client + Load func() (float64, error) + Pins []ToolPin + Now func() time.Time +} + +func (c *Config) logf(format string, a ...any) { + if c.Log != nil { + fmt.Fprintf(c.Log, format+"\n", a...) + } +} + +// Execute runs the benchmark and returns the results; it also writes them to +// Work/results.json. +func Execute(ctx context.Context, cfg Config) (*Results, error) { + if cfg.Frames < 2 || cfg.Frames > PinFrames { + return nil, fmt.Errorf("frames must be between 2 and %d (the flicker proxy needs a pair)", PinFrames) + } + if cfg.Exec == nil { + cfg.Exec = OSExec{} + } + if cfg.Now == nil { + cfg.Now = time.Now + } + if cfg.Jobs < 1 { + cfg.Jobs = 1 + } + res := &Results{Schema: SchemaVersion, Tool: cfg.Version, Started: cfg.Now().UTC(), Frames: cfg.Frames, + Tools: map[string]string{}} + host, _ := os.Hostname() + res.Machine = Machine{Hostname: host, OS: runtime.GOOS, Arch: runtime.GOARCH, CPUs: runtime.NumCPU(), + MaxLoad: cfg.MaxLoad, LoadWaiver: cfg.LoadWaiver, Note: cfg.Note, LoadStart: -1, LoadEnd: -1} + if cfg.Load != nil { + l, err := cfg.Load() + if err == nil { + res.Machine.LoadStart = l + } + switch { + case err != nil && cfg.LoadWaiver == "": + return nil, fmt.Errorf("cannot read the load average (%v): timings are not valid without it; pass --load-waiver REASON to go on", err) + case err == nil && cfg.MaxLoad > 0 && l > cfg.MaxLoad && cfg.LoadWaiver == "": + return nil, fmt.Errorf("one-minute load %.1f is above the limit %.1f: timings taken now would measure the machine, not the tools; wait, or pass --load-waiver REASON (it is stamped into the results)", l, cfg.MaxLoad) + } + } + if err := os.MkdirAll(cfg.Work, 0o755); err != nil { + return nil, err + } + if err := cfg.recordTools(ctx, res); err != nil { + return nil, err + } + for _, c := range cfg.Clips { + if len(cfg.Only) > 0 && !contains(cfg.Only, c.Name) { + continue + } + info, runs, err := cfg.doClip(ctx, c, res.Tools) + if err != nil { + return nil, fmt.Errorf("clip %s: %w", c.Name, err) + } + res.Clips = append(res.Clips, info) + res.Runs = append(res.Runs, runs...) + } + if cfg.Load != nil { + if l, err := cfg.Load(); err == nil { + res.Machine.LoadEnd = l + } + } + res.Finished = cfg.Now().UTC() + js, err := json.MarshalIndent(res, "", " ") + if err != nil { + return nil, err + } + if err := os.WriteFile(filepath.Join(cfg.Work, "results.json"), append(js, '\n'), 0o644); err != nil { + return nil, err + } + return res, nil +} + +func contains(l []string, s string) bool { + for _, x := range l { + if x == s { + return true + } + } + return false +} + +// recordTools stores the version of every tool and checks the pinned ones. +func (cfg *Config) recordTools(ctx context.Context, res *Results) error { + for _, t := range []struct{ key, bin, flag string }{ + {"ffmpeg", cfg.FFmpeg, "-version"}, {"vtracer", cfg.VTracer, "--version"}, {"resvg", cfg.Resvg, "--version"}, + } { + r, err := cfg.Exec.Run(ctx, t.bin, t.flag) + if err != nil { + return fmt.Errorf("%s: %w", t.key, err) + } + res.Tools[t.key] = ParseVersionLine(r.Out) + } + for _, p := range cfg.Pins { + got, ok := res.Tools[p.Name] + if ok && strings.Contains(got, p.Version) { + continue + } + if !cfg.AllowUnpinned { + return fmt.Errorf("%s reports %q, the pinned version is %q (%s); install that one, or pass --allow-unpinned-tools", p.Name, got, p.Version, p.Source) + } + res.Tools[p.Name+"_unpinned"] = "pin " + p.Version + " not met" + } + return nil +} + +var encVersion = map[string]*regexp.Regexp{ + "x264": regexp.MustCompile(`x264 - core \d+[^\n]*`), + "x265": regexp.MustCompile(`HEVC encoder version[^\n]*`), + "svtav1": regexp.MustCompile(`SVT \[version\][^\n]*`), + "vp9": regexp.MustCompile(`libvpx-vp9[^\n]*|Lavc[^\n]*libvpx[^\n]*`), +} + +func (cfg *Config) doClip(ctx context.Context, c Clip, tools map[string]string) (ClipInfo, []Run, error) { + dir := filepath.Join(cfg.Work, c.Name) + info := ClipInfo{Name: c.Name, Class: c.Class, URL: c.URL, SHA256: c.SHA256, FPS: c.FPS} + raw := filepath.Join(dir, "prefix.y4m") + if !fileExists(raw) { + cfg.logf("%s: fetching the first %d frames", c.Name, PinFrames) + got, err := FetchPrefix(ctx, cfg.Client, c.URL, PinFrames, raw) + if err != nil { + return info, nil, err + } + if err := VerifyPin(c.Name, got, c.SHA256); err != nil { + os.Remove(raw) + return info, nil, err + } + } + hdr, err := readHeader(raw) + if err != nil { + return info, nil, err + } + info.Width, info.Height = hdr.Width, hdr.Height + n := cfg.Frames + src := filepath.Join(dir, "src.y4m") + pngDir := filepath.Join(dir, "png") + if !fileExists(src) { + if _, err := cfg.Exec.Run(ctx, cfg.FFmpeg, "-hide_banner", "-nostdin", "-y", "-i", raw, + "-frames:v", strconv.Itoa(n), "-pix_fmt", "yuv420p", src+".part.y4m"); err != nil { + return info, nil, err + } + if err := os.Rename(src+".part.y4m", src); err != nil { + return info, nil, err + } + } + if !fileExists(filepath.Join(pngDir, frameName("f_%03d.png", n))) { + if err := os.MkdirAll(pngDir, 0o755); err != nil { + return info, nil, err + } + if _, err := cfg.Exec.Run(ctx, cfg.FFmpeg, "-hide_banner", "-nostdin", "-y", "-i", src, + filepath.Join(pngDir, "f_%03d.png")); err != nil { + return info, nil, err + } + } + var runs []Run + var pngBytes int64 + for i := 1; i <= n; i++ { + st, err := os.Stat(filepath.Join(pngDir, frameName("f_%03d.png", i))) + if err != nil { + return info, nil, err + } + pngBytes += st.Size() + } + runs = append(runs, Run{Clip: c.Name, Class: c.Class, Variant: "PNG lossless", Family: "png", Frames: n, + Bytes: pngBytes, PSNR: PSNRInf, VMAF: 100}) + for vi, v := range cfg.Variant { + cache := filepath.Join(dir, fmt.Sprintf("run_%02d_%d.json", vi, n)) + if b, err := os.ReadFile(cache); err == nil { + var r Run + if json.Unmarshal(b, &r) == nil && r.Variant == v.Label && r.Frames == n { + runs = append(runs, r) + continue + } + } + r := Run{Clip: c.Name, Class: c.Class, Variant: v.Label, Family: v.Family, Frames: n} + if cfg.Load != nil { + if l, err := cfg.Load(); err == nil { + r.Load1 = l + } + } + if v.Vector() { + err = cfg.doVector(ctx, &r, v, dir, pngDir, src, vi, c.FPS) + } else { + err = cfg.doEncode(ctx, &r, v, dir, src, vi, tools) + } + if err != nil { + return info, nil, fmt.Errorf("%s: %w", v.Label, err) + } + b, _ := json.Marshal(r) + if err := os.WriteFile(cache, b, 0o644); err != nil { + return info, nil, err + } + cfg.logf("%s / %s: %d B, PSNR %.2f, VMAF %.1f", c.Name, v.Label, r.Bytes, r.PSNR, r.VMAF) + runs = append(runs, r) + } + return info, runs, nil +} + +func frameName(pattern string, i int) string { return fmt.Sprintf(pattern, i) } + +func fileExists(p string) bool { _, err := os.Stat(p); return err == nil } + +func readHeader(path string) (Y4M, error) { + f, err := os.Open(path) + if err != nil { + return Y4M{}, err + } + defer f.Close() + b, err := io.ReadAll(io.LimitReader(f, MaxHeaderLen)) + if err != nil { + return Y4M{}, err + } + return ParseY4MHeader(b) +} + +func (cfg *Config) doEncode(ctx context.Context, r *Run, v Variant, dir, src string, vi int, tools map[string]string) error { + enc := filepath.Join(dir, fmt.Sprintf("enc_%02d.%s", vi, v.Ext)) + args := append([]string{"-hide_banner", "-nostdin", "-y", "-i", src}, v.Args...) + args = append(args, "-pix_fmt", "yuv420p", "-an", enc) + er, err := cfg.Exec.Run(ctx, cfg.FFmpeg, args...) + if err != nil { + return err + } + r.EncodeWallS, r.EncodeCPUS = er.Wall.Seconds(), er.CPU.Seconds() + if re := encVersion[v.Family]; re != nil { + if m := re.FindString(er.Out); m != "" { + tools[v.Family] = strings.TrimSpace(m) + } + } + st, err := os.Stat(enc) + if err != nil { + return err + } + r.Bytes = st.Size() + r.PSNR, r.VMAF, err = cfg.quality(ctx, []string{"-i", enc}, src) + return err +} + +// quality compares a distorted input against the lossless source and returns +// PSNR and VMAF. +func (cfg *Config) quality(ctx context.Context, distArgs []string, src string) (float64, float64, error) { + args := append([]string{"-hide_banner", "-nostdin"}, distArgs...) + args = append(args, "-i", src, "-lavfi", + // Both inputs are re-stamped by frame index: containers with a + // millisecond time base (mkv, webm) otherwise pair frame k with + // frame k-1 of the y4m source and report a false ~29 dB. + "[0:v]format=yuv420p,settb=1/1000,setpts=N,split[a][b];[1:v]format=yuv420p,settb=1/1000,setpts=N,split[c][d];[a][c]psnr;[b][d]libvmaf=n_threads=4", + "-f", "null", "-") + r, err := cfg.Exec.Run(ctx, cfg.FFmpeg, args...) + if err != nil { + return 0, 0, err + } + p, err := ParsePSNR(r.Out) + if err != nil { + return 0, 0, err + } + vm, err := ParseVMAF(r.Out) + return p, vm, err +} + +func (cfg *Config) doVector(ctx context.Context, r *Run, v Variant, dir, pngDir, src string, vi int, fps float64) error { + n := r.Frames + svgDir := filepath.Join(dir, fmt.Sprintf("svg_%02d_%d", vi, n)) + if err := os.MkdirAll(svgDir, 0o755); err != nil { + return err + } + var ( + wg sync.WaitGroup + mu sync.Mutex + sem = make(chan struct{}, cfg.Jobs) + errs = make([]error, n+1) + ) + for i := 1; i <= n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + in := filepath.Join(pngDir, frameName("f_%03d.png", i)) + svg := filepath.Join(svgDir, frameName("f_%03d.svg", i)) + png := filepath.Join(svgDir, frameName("r_%03d.png", i)) + args := append([]string{"--input", in, "--output", svg}, v.Args...) + vr, err := cfg.Exec.Run(ctx, cfg.VTracer, args...) + if err != nil { + errs[i] = err + return + } + mu.Lock() + r.VectoriseWallS += vr.Wall.Seconds() + r.VectoriseCPUS += vr.CPU.Seconds() + mu.Unlock() + _, errs[i] = cfg.Exec.Run(ctx, cfg.Resvg, svg, png) + }(i) + } + wg.Wait() + for _, e := range errs { + if e != nil { + return e + } + } + var prev []Path + var churns []Churn + var sum int + r.PathsMin = -1 + for i := 1; i <= n; i++ { + b, err := os.ReadFile(filepath.Join(svgDir, frameName("f_%03d.svg", i))) + if err != nil { + return err + } + r.Bytes += int64(len(b)) + r.GzipBytes += gzipLen(b) + paths, err := ParsePaths(b) + if err != nil { + return fmt.Errorf("frame %d: %w", i, err) + } + k := len(paths) + sum += k + if r.PathsMin < 0 || k < r.PathsMin { + r.PathsMin = k + } + if k > r.PathsMax { + r.PathsMax = k + } + if i > 1 { + churns = append(churns, MatchPaths(prev, paths)) + } + prev = paths + } + r.PathsMean = float64(sum) / float64(n) + cs := Summarise(churns) + r.Churn = &cs + var err error + r.PSNR, r.VMAF, err = cfg.quality(ctx, []string{"-framerate", strconv.FormatFloat(fps, 'f', -1, 64), + "-i", filepath.Join(svgDir, "r_%03d.png")}, src) + return err +} + +func gzipLen(b []byte) int64 { + var buf bytes.Buffer + w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) + w.Write(b) + w.Close() + return int64(buf.Len()) +} diff --git a/internal/bench/runner_fail_test.go b/internal/bench/runner_fail_test.go new file mode 100644 index 0000000..b3cea53 --- /dev/null +++ b/internal/bench/runner_fail_test.go @@ -0,0 +1,202 @@ +package bench + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" +) + +const vt = "visioncortex VTracer 0.6.5" + +// Every step of a run can fail; each failure must reach the caller with the +// tool's own message, not be swallowed or replaced. +func TestExecuteStepFailures(t *testing.T) { + cases := []struct { + name string + fx fakeExec + }{ + {"ffmpeg probe", fakeExec{fail: "ffmpeg -version"}}, + {"vtracer probe", fakeExec{fail: "vtracer --version"}}, + {"resvg probe", fakeExec{fail: "resvg --version"}}, + {"source conversion", fakeExec{fail: "part.y4m"}}, + {"png extraction", fakeExec{fail: "f_%03d.png"}}, + {"encode", fakeExec{fail: "libx264"}}, + {"quality of an encode", fakeExec{fail: "-lavfi"}}, + {"vtracer run", fakeExec{fail: "--input"}}, + {"resvg run", fakeExec{fail: "r_002.png"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + fx := c.fx + fx.vtVer = vt + cfg := testConfig(t, &fx, 1) + _, err := Execute(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), "boom") { + t.Fatalf("got %v", err) + } + }) + } +} + +func TestExecuteBadOutputs(t *testing.T) { + cases := []struct { + name string + fx fakeExec + want string + }{ + {"source not written", fakeExec{skip: "part.y4m"}, "part.y4m"}, + {"frames not written", fakeExec{skip: "f_%03d.png"}, "f_001.png"}, + {"encode not written", fakeExec{skip: "libx264"}, "enc_00"}, + {"vector not written", fakeExec{skip: "--output"}, "f_001.svg"}, + {"malformed svg", fakeExec{badSVG: true}, "frame 1"}, + {"no psnr", fakeExec{say: "-lavfi", sayOut: "nothing\n"}, "PSNR"}, + {"no vmaf", fakeExec{say: "-lavfi", sayOut: "[psnr] PSNR average:30.00\n"}, "VMAF"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + fx := c.fx + fx.vtVer = vt + cfg := testConfig(t, &fx, 1) + _, err := Execute(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("want %q, got %v", c.want, err) + } + }) + } + t.Run("vector quality", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vt, fail: "r_%03d.png"}, 1) + cfg.Variant = cfg.Variant[1:] + if _, err := Execute(context.Background(), cfg); err == nil || !strings.Contains(err.Error(), "boom") { + t.Fatalf("got %v", err) + } + }) +} + +func TestExecuteFilesystemFailures(t *testing.T) { + ctx := context.Background() + mk := func(t *testing.T) Config { return testConfig(t, &fakeExec{vtVer: vt}, 1) } + dir := func(t *testing.T, p ...string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(p...), 0o755); err != nil { + t.Fatal(err) + } + } + file := func(t *testing.T, p ...string) { + t.Helper() + pp := filepath.Join(p...) + if err := os.MkdirAll(filepath.Dir(pp), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(pp, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + t.Run("work under a file", func(t *testing.T) { + cfg := mk(t) + file(t, cfg.Work, "f") + cfg.Work = filepath.Join(cfg.Work, "f", "sub") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("png dir is a file", func(t *testing.T) { + cfg := mk(t) + file(t, cfg.Work, "c1", "png") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("cache path is a directory", func(t *testing.T) { + cfg := mk(t) + dir(t, cfg.Work, "c1", "run_00_3.json") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("svg dir is a file", func(t *testing.T) { + cfg := mk(t) + file(t, cfg.Work, "c1", "svg_01_3") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("results is a directory", func(t *testing.T) { + cfg := mk(t) + dir(t, cfg.Work, "results.json", "x") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("prefix is garbage", func(t *testing.T) { + cfg := mk(t) + file(t, cfg.Work, "c1", "prefix.y4m") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("prefix is a directory", func(t *testing.T) { + cfg := mk(t) + dir(t, cfg.Work, "c1", "prefix.y4m") + if _, err := Execute(ctx, cfg); err == nil { + t.Fatal("accepted") + } + }) + t.Run("prefix unreadable", func(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("permissions are not enforced here") + } + cfg := mk(t) + file(t, cfg.Work, "c1", "prefix.y4m") + p := filepath.Join(cfg.Work, "c1", "prefix.y4m") + if err := os.Chmod(p, 0); err != nil { + t.Fatal(err) + } + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "permission") { + t.Fatalf("got %v", err) + } + }) + t.Run("fetch fails", func(t *testing.T) { + cfg := mk(t) + cfg.Clips[0].URL = "http://127.0.0.1:1/none.y4m" + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "clip c1") { + t.Fatalf("got %v", err) + } + }) + t.Run("load is not a number", func(t *testing.T) { + cfg := mk(t) + cfg.Load = func() (float64, error) { return nan(), nil } + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "NaN") { + t.Fatalf("got %v", err) + } + }) +} + +func nan() float64 { var z float64; return z / z } + +func TestExecuteLoadReadLater(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vt}, 1) + var n atomic.Int32 + cfg.Load = func() (float64, error) { + if n.Add(1) == 1 { + return 2, nil + } + return 0, errors.New("gone") + } + res, err := Execute(context.Background(), cfg) + if err != nil { + t.Fatal(err) + } + if res.Machine.LoadStart != 2 || res.Machine.LoadEnd != -1 { + t.Fatalf("%+v", res.Machine) + } + for _, r := range res.Runs { + if r.Load1 != 0 { + t.Fatalf("a failed read was recorded: %+v", r) + } + } +} diff --git a/internal/bench/runner_test.go b/internal/bench/runner_test.go new file mode 100644 index 0000000..df1b07c --- /dev/null +++ b/internal/bench/runner_test.go @@ -0,0 +1,263 @@ +package bench + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +var fakeMu sync.Mutex + +// fakeExec stands in for ffmpeg, vtracer and resvg: it writes the files the +// real programs would and prints the summaries the parsers read. +type fakeExec struct { + calls []string + vtVer string + fail string // substring of a command line that fails + skip string // substring of a command line that succeeds and writes nothing + say string // substring of a command line whose output is replaced by sayOut + sayOut string + badSVG bool // vtracer writes an SVG whose path data is malformed +} + +func (f *fakeExec) Run(_ context.Context, name string, args ...string) (ExecResult, error) { + line := name + " " + strings.Join(args, " ") + fakeMu.Lock() + f.calls = append(f.calls, line) + fakeMu.Unlock() + if f.fail != "" && strings.Contains(line, f.fail) { + return ExecResult{}, errors.New("boom") + } + res := ExecResult{Wall: 2 * time.Second, CPU: time.Second} + if f.skip != "" && strings.Contains(line, f.skip) { + return res, nil + } + if f.say != "" && strings.Contains(line, f.say) { + res.Out = f.sayOut + return res, nil + } + switch { + case strings.HasSuffix(name, "vtracer") && len(args) == 1: + res.Out = f.vtVer + "\n" + case strings.HasSuffix(name, "resvg") && len(args) == 1: + res.Out = "0.50.0\n" + case strings.HasSuffix(name, "resvg"): + return res, os.WriteFile(args[1], []byte("png"), 0o644) + case strings.HasSuffix(name, "vtracer"): + frame := args[1] + d := "M0 0 L10 0 L10 10 L0 10 Z" + if strings.Contains(frame, "f_002") { + d = "M0 0 L50 0 L50 50 L0 50 Z" // frame 2 differs: churn > 0 + } + if f.badSVG { + d = "M 1" + } + svg := fmt.Sprintf(``, d) + return res, os.WriteFile(args[3], []byte(svg), 0o644) + case len(args) == 1 && args[0] == "-version": + res.Out = "ffmpeg version fake\nconfiguration: --enable-libvmaf\n" + case contains(args, "-lavfi"): + q := 30.0 + if strings.Contains(line, "svg_") { + q = 20 + } + res.Out = fmt.Sprintf("[psnr] PSNR average:%.2f\n[libvmaf] VMAF score: %.2f\n", q, q*2) + case contains(args, "-pix_fmt") && strings.HasSuffix(args[len(args)-1], ".part.y4m"): + return res, os.WriteFile(args[len(args)-1], []byte("y4m"), 0o644) + case strings.HasSuffix(args[len(args)-1], "f_%03d.png"): + dir := filepath.Dir(args[len(args)-1]) + for i := 1; i <= PinFrames; i++ { + if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("f_%03d.png", i)), []byte("p"), 0o644); err != nil { + return res, err + } + } + case args[len(args)-1] == "-": // a null sink writes nothing + default: // an encode: the last argument is the output file + res.Out = "x264 - core 164 r3191\n" + return res, os.WriteFile(args[len(args)-1], bytes.Repeat([]byte("e"), 100), 0o644) + } + return res, nil +} + +func testServer(t *testing.T) (*httptest.Server, string) { + t.Helper() + b := []byte("YUV4MPEG2 W4 H2 F1:1 C420\n") + for i := 0; i < PinFrames; i++ { + b = append(b, "FRAME\n"...) + b = append(b, make([]byte, 12)...) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.ServeContent(w, r, "c.y4m", time.Time{}, bytes.NewReader(b)) + })) + t.Cleanup(srv.Close) + sum := sha256.Sum256(b) + return srv, hex.EncodeToString(sum[:]) +} + +func testConfig(t *testing.T, fx *fakeExec, load float64) Config { + srv, sum := testServer(t) + pins, err := ToolPins() + if err != nil { + t.Fatal(err) + } + return Config{ + Work: t.TempDir(), Frames: 3, FFmpeg: "ffmpeg", VTracer: "vtracer", Resvg: "resvg", + Clips: []Clip{{Name: "c1", Class: "screen", URL: srv.URL, FPS: 30, SHA256: sum}}, + Variant: []Variant{ + {"x264 crf23", "x264", []string{"-c:v", "libx264", "-crf", "23"}, "mp4"}, + {"vtracer default", "vtracer", nil, "svg"}, + }, + MaxLoad: 8, Version: "vtest", Exec: fx, Client: srv.Client(), Pins: pins, + Load: func() (float64, error) { return load, nil }, + Now: func() time.Time { return time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC) }, + } +} + +func TestExecuteWithFakes(t *testing.T) { + fx := &fakeExec{vtVer: "visioncortex VTracer 0.6.5"} + cfg := testConfig(t, fx, 1.5) + res, err := Execute(context.Background(), cfg) + if err != nil { + t.Fatal(err) + } + if res.Machine.LoadStart != 1.5 || res.Machine.MaxLoad != 8 || res.Tools["vtracer"] != "visioncortex VTracer 0.6.5" || res.Tools["x264"] == "" { + t.Fatalf("machine/tools: %+v %+v", res.Machine, res.Tools) + } + if len(res.Runs) != 3 || res.Clips[0].Width != 4 || res.Clips[0].SHA256 != cfg.Clips[0].SHA256 { + t.Fatalf("%d runs, clip %+v", len(res.Runs), res.Clips) + } + png, enc, vec := res.Runs[0], res.Runs[1], res.Runs[2] + if png.Family != "png" || png.Bytes != 3 || png.VMAF != 100 { + t.Errorf("png: %+v", png) + } + if enc.Bytes != 100 || enc.EncodeWallS != 2 || enc.EncodeCPUS != 1 || enc.PSNR != 30 || enc.VMAF != 60 || enc.Load1 != 1.5 { + t.Errorf("encode: %+v", enc) + } + if !vec.Vector() || vec.PathsMean != 2 || vec.PathsMin != 2 || vec.VectoriseWallS != 6 || vec.PSNR != 20 || vec.GzipBytes == 0 { + t.Errorf("vector: %+v", vec) + } + // frames 1->2 change the red box (10x10 -> 50x50), 2->3 changes it back + if vec.Churn == nil || vec.Churn.Pairs != 2 || vec.Churn.Churn <= 0 || vec.Churn.Churn >= 1 { + t.Errorf("churn: %+v", vec.Churn) + } + if _, err := os.Stat(filepath.Join(cfg.Work, "results.json")); err != nil { + t.Error(err) + } + // A second run reads every variant from the cache: no encoder, no vtracer. + before := len(fx.calls) + if _, err := Execute(context.Background(), cfg); err != nil { + t.Fatal(err) + } + for _, c := range fx.calls[before:] { + if strings.Contains(c, "libx264") || strings.Contains(c, "--output") { + t.Fatalf("not cached: %s", c) + } + } + b, _ := os.ReadFile(filepath.Join(cfg.Work, "results.json")) + if _, err := ParseResults(b); err != nil { + t.Fatal(err) + } +} + +func TestExecuteRefusals(t *testing.T) { + ctx := context.Background() + t.Run("load above the limit", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: "VTracer 0.6.5"}, 90) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "above the limit") { + t.Fatalf("%v", err) + } + cfg.LoadWaiver = "fractal unavailable" + res, err := Execute(ctx, cfg) + if err != nil || res.Machine.LoadWaiver != "fractal unavailable" { + t.Fatalf("%v", err) + } + }) + t.Run("load unreadable", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: "VTracer 0.6.5"}, 0) + cfg.Load = func() (float64, error) { return 0, errors.New("no source") } + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "load average") { + t.Fatalf("%v", err) + } + }) + t.Run("unpinned VTracer", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: "visioncortex VTracer 0.5.0"}, 1) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "pinned version") { + t.Fatalf("%v", err) + } + cfg.AllowUnpinned = true + res, err := Execute(ctx, cfg) + if err != nil || res.Tools["vtracer_unpinned"] == "" { + t.Fatalf("%v %v", err, res) + } + }) + t.Run("wrong clip hash", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vtProbe()}, 1) + cfg.Clips[0].SHA256 = strings.Repeat("0", 64) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "mismatch") { + t.Fatalf("%v", err) + } + if fileExists(filepath.Join(cfg.Work, "c1", "prefix.y4m")) { + t.Fatal("a clip that failed its pin was kept") + } + }) + t.Run("no hash pinned", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vtProbe()}, 1) + cfg.Clips[0].SHA256 = "" + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "no pinned SHA-256") { + t.Fatalf("%v", err) + } + }) + t.Run("frames out of range", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vtProbe()}, 1) + for _, n := range []int{1, PinFrames + 1} { + cfg.Frames = n + if _, err := Execute(ctx, cfg); err == nil { + t.Fatalf("frames %d accepted", n) + } + } + }) + t.Run("a failing tool names the variant", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: "VTracer 0.6.5", fail: "libx264"}, 1) + if _, err := Execute(ctx, cfg); err == nil || !strings.Contains(err.Error(), "x264 crf23") { + t.Fatalf("%v", err) + } + }) + t.Run("only", func(t *testing.T) { + cfg := testConfig(t, &fakeExec{vtVer: vtProbe()}, 1) + cfg.Only = []string{"other"} + res, err := Execute(ctx, cfg) + if err != nil || len(res.Runs) != 0 { + t.Fatalf("%v %v", err, res) + } + }) +} + +func vtProbe() string { return "visioncortex VTracer 0.6.5" } + +func TestOSExec(t *testing.T) { + r, err := OSExec{}.Run(context.Background(), "go", "version") + if err != nil || !strings.Contains(r.Out, "go version") || r.Wall <= 0 { + t.Fatalf("%v %+v", err, r) + } + if _, err := (OSExec{}).Run(context.Background(), "go", "no-such-subcommand"); err == nil { + t.Fatal("failure not reported") + } + var tl tail + big := bytes.Repeat([]byte("x"), 3*tailLimit) + tl.Write(big) + tl.Write([]byte("END")) + if s := tl.String(); len(s) != tailLimit || !strings.HasSuffix(s, "END") { + t.Fatalf("tail kept %d bytes", len(s)) + } +} diff --git a/internal/bench/svgpaths.go b/internal/bench/svgpaths.go new file mode 100644 index 0000000..1da142c --- /dev/null +++ b/internal/bench/svgpaths.go @@ -0,0 +1,273 @@ +package bench + +import ( + "bytes" + "errors" + "fmt" + "math" + "strconv" + "strings" +) + +// Bounds on an SVG we are willing to read: the files come from a tool we ran, +// but the parser is also fuzzed with arbitrary input. +const ( + MaxSVGBytes = 512 << 20 + MaxSVGPaths = 5_000_000 +) + +// The limits in force; tests lower them to reach the refusals. +var ( + svgBytesLimit = MaxSVGBytes + svgPathsLimit = MaxSVGPaths +) + +// Path is one of a VTracer SVG, reduced to what the flicker proxy +// compares: the fill colour and the bounding box of its control points. +type Path struct { + R, G, B uint8 + X0, Y0, X1, Y1 float64 +} + +// Area of the bounding box. +func (p Path) Area() float64 { return (p.X1 - p.X0) * (p.Y1 - p.Y0) } + +// CX is the horizontal centre of the box. +func (p Path) CX() float64 { return (p.X0 + p.X1) / 2 } + +// CY is the vertical centre of the box. +func (p Path) CY() float64 { return (p.Y0 + p.Y1) / 2 } + +// ParsePaths reads the elements of an SVG. An element without a d +// attribute or whose d holds no coordinate is skipped; a malformed number in d +// is an error. A missing or unreadable fill is black. +func ParsePaths(svg []byte) ([]Path, error) { + if len(svg) > svgBytesLimit { + return nil, errors.New("svg: file larger than the limit") + } + var out []Path + rest := svg + for { + i := bytes.Index(rest, []byte(" 0 && rest[0] != ' ' && rest[0] != '\n' && rest[0] != '\t' && rest[0] != '\r' && rest[0] != '/' && rest[0] != '>' { + continue // + } + end := bytes.IndexByte(rest, '>') + if end < 0 { + return out, nil + } + tag := string(rest[:end]) + rest = rest[end:] + d, ok := attr(tag, "d") + if !ok { + continue + } + bb, ok, err := pathBBox(d) + if err != nil { + return nil, err + } + if !ok { + continue + } + p := Path{X0: bb[0], Y0: bb[1], X1: bb[2], Y1: bb[3]} + if f, ok := attr(tag, "fill"); ok { + p.R, p.G, p.B = parseHexColor(f) + } + if t, ok := attr(tag, "transform"); ok { + if dx, dy, ok := parseTranslate(t); ok { + p.X0 += dx + p.X1 += dx + p.Y0 += dy + p.Y1 += dy + } + } + if len(out) >= svgPathsLimit { + return nil, errors.New("svg: more paths than the limit") + } + out = append(out, p) + } +} + +// attr returns the value of name="..." in a tag body, matching the whole +// attribute name. +func attr(tag, name string) (string, bool) { + key := name + `="` + from := 0 + for { + i := strings.Index(tag[from:], key) + if i < 0 { + return "", false + } + i += from + if i == 0 || tag[i-1] == ' ' || tag[i-1] == '\n' || tag[i-1] == '\t' || tag[i-1] == '\r' { + s := tag[i+len(key):] + j := strings.IndexByte(s, '"') + if j < 0 { + return "", false + } + return s[:j], true + } + from = i + 1 + } +} + +func parseHexColor(s string) (r, g, b uint8) { + s = strings.TrimPrefix(strings.TrimSpace(s), "#") + if len(s) == 3 { + s = string([]byte{s[0], s[0], s[1], s[1], s[2], s[2]}) + } + if len(s) != 6 { + return 0, 0, 0 + } + // Six characters cannot overflow 32 bits, and a syntax error leaves v at 0: + // an unreadable colour is black. + v, _ := strconv.ParseUint(s, 16, 32) + return uint8(v >> 16), uint8(v >> 8), uint8(v) +} + +func parseTranslate(s string) (dx, dy float64, ok bool) { + s = strings.TrimSpace(s) + if !strings.HasPrefix(s, "translate(") || !strings.HasSuffix(s, ")") { + return 0, 0, false + } + inner := s[len("translate(") : len(s)-1] + a, i, ok1 := scanNumber(inner, 0) + if !ok1 { + return 0, 0, false + } + b, _, ok2 := scanNumber(inner, i) + if !ok2 { + b = 0 + } + return a, b, true +} + +// scanNumber reads one SVG number at or after i (skipping separators). +func scanNumber(s string, i int) (float64, int, bool) { + for i < len(s) && (s[i] == ' ' || s[i] == ',' || s[i] == '\n' || s[i] == '\t' || s[i] == '\r') { + i++ + } + start := i + if i < len(s) && (s[i] == '-' || s[i] == '+') { + i++ + } + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + if i < len(s) && s[i] == '.' { + i++ + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + } + // No digit at all ("-", ".", "e5") is left to ParseFloat, which refuses it. + if i < len(s) && (s[i] == 'e' || s[i] == 'E') { + j := i + 1 + if j < len(s) && (s[j] == '-' || s[j] == '+') { + j++ + } + k := j + for k < len(s) && s[k] >= '0' && s[k] <= '9' { + k++ + } + if k > j { + i = k + } + } + v, err := strconv.ParseFloat(s[start:i], 64) + if err != nil || math.IsInf(v, 0) || math.IsNaN(v) { + return 0, start, false + } + return v, i, true +} + +// argCount is the number of numbers each path command takes. +var argCount = map[byte]int{'M': 2, 'L': 2, 'H': 1, 'V': 1, 'C': 6, 'S': 4, 'Q': 4, 'T': 2, 'A': 7, 'Z': 0} + +// pathBBox is the bounding box [x0 y0 x1 y1] of every coordinate of a path +// data string, control points included. ok is false when it holds none. +func pathBBox(d string) ([4]float64, bool, error) { + bb := [4]float64{math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)} + add := func(x, y float64) { + bb[0], bb[1] = math.Min(bb[0], x), math.Min(bb[1], y) + bb[2], bb[3] = math.Max(bb[2], x), math.Max(bb[3], y) + } + var cx, cy, sx, sy float64 + var cmd byte + i := 0 + for { + for i < len(d) && (d[i] == ' ' || d[i] == ',' || d[i] == '\n' || d[i] == '\t' || d[i] == '\r') { + i++ + } + if i >= len(d) { + break + } + c := d[i] + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') { + up := c &^ 0x20 + if _, ok := argCount[up]; !ok { + return bb, false, fmt.Errorf("svg: unknown path command %q", c) + } + cmd = c + i++ + if up == 'Z' { + cx, cy = sx, sy + cmd = 0 + } + continue + } + if cmd == 0 { + return bb, false, errors.New("svg: coordinates before a command") + } + up := cmd &^ 0x20 + rel := cmd >= 'a' + n := argCount[up] + var a [7]float64 + for k := 0; k < n; k++ { + v, j, ok := scanNumber(d, i) + if !ok { + return bb, false, fmt.Errorf("svg: bad number near offset %d", j) + } + a[k], i = v, j + } + ox, oy := 0.0, 0.0 + if rel { + ox, oy = cx, cy + } + switch up { + case 'M', 'L', 'T': + cx, cy = a[0]+ox, a[1]+oy + add(cx, cy) + if up == 'M' { + sx, sy = cx, cy + cmd = 'L' | (cmd & 0x20) + } + case 'H': + cx = a[0] + ox + add(cx, cy) + case 'V': + cy = a[0] + oy + add(cx, cy) + case 'C': + add(a[0]+ox, a[1]+oy) + add(a[2]+ox, a[3]+oy) + cx, cy = a[4]+ox, a[5]+oy + add(cx, cy) + case 'S', 'Q': + add(a[0]+ox, a[1]+oy) + cx, cy = a[2]+ox, a[3]+oy + add(cx, cy) + case 'A': + cx, cy = a[5]+ox, a[6]+oy + add(cx, cy) + } + } + if math.IsInf(bb[0], 1) { + return bb, false, nil + } + return bb, true, nil +} diff --git a/internal/bench/svgpaths_test.go b/internal/bench/svgpaths_test.go new file mode 100644 index 0000000..da343fe --- /dev/null +++ b/internal/bench/svgpaths_test.go @@ -0,0 +1,122 @@ +package bench + +import ( + "math" + "strings" + "testing" +) + +const sampleSVG = ` + + + + + +` + +func TestParsePaths(t *testing.T) { + ps, err := ParsePaths([]byte(sampleSVG)) + if err != nil { + t.Fatal(err) + } + if len(ps) != 2 { + t.Fatalf("%d paths: %+v", len(ps), ps) + } + a, b := ps[0], ps[1] + if a.R != 255 || a.G != 0 || a.X0 != 0 || a.X1 != 8 || a.Y1 != 6 { + t.Fatalf("%+v", a) + } + if b.R != 10 || b.G != 11 || b.B != 12 || b.X0 != 3 || b.X1 != 5 || b.Y0 != 1 || b.Y1 != 3 { + t.Fatalf("%+v", b) + } + if a.Area() != 48 || a.CX() != 4 || a.CY() != 3 { + t.Fatal("geometry") + } +} + +func TestPathBBoxCommands(t *testing.T) { + cases := []struct { + d string + want [4]float64 + }{ + {"M1 2 L3 4", [4]float64{1, 2, 3, 4}}, + {"m1 2 l2 2", [4]float64{1, 2, 3, 4}}, + {"M0,0 H5 V7", [4]float64{0, 0, 5, 7}}, + {"M0 0 h5 v-7", [4]float64{0, -7, 5, 0}}, + {"M0 0 1 1 2 0", [4]float64{0, 0, 2, 1}}, // implicit lineto + {"M0 0 Q1 5 2 0", [4]float64{0, 0, 2, 5}}, // control point counts + {"M0 0 A1 1 0 0 1 4 4", [4]float64{0, 0, 4, 4}}, // arc: endpoint + {"M-1.5e1 .5-2 0", [4]float64{-15, 0, -2, 0.5}}, // exponent, leading dot, packed sign + {"M0 0 Z L2 2", [4]float64{0, 0, 2, 2}}, // Z returns to the start + {"M5 5 c1 1 2 2 3 3 z m1 1", [4]float64{5, 5, 8, 8}}, // relative after close + } + for _, c := range cases { + got, ok, err := pathBBox(c.d) + if err != nil || !ok || got != c.want { + t.Errorf("%q: %v ok=%v err=%v, want %v", c.d, got, ok, err, c.want) + } + } + if _, ok, err := pathBBox("Z"); ok || err != nil { + t.Error("Z alone has no box and is not an error") + } + for _, bad := range []string{"M0 x", "5 5", "M0 0 L1", "M0 0 K1 1", "M0 0 L1e999 0"} { + if _, _, err := pathBBox(bad); err == nil { + t.Errorf("%q accepted", bad) + } + } +} + +func TestParsePathsLimits(t *testing.T) { + if _, err := ParsePaths([]byte(``)); err == nil { + t.Error("bad d accepted") + } + ps, err := ParsePaths([]byte(``)) + if err != nil || len(ps) != 3 { + t.Fatalf("%v %d", err, len(ps)) + } + if ps[0].R != 0xaa || ps[0].G != 0xbb || ps[0].B != 0xcc { + t.Errorf("short colour: %+v", ps[0]) + } + if ps[1].R != 0 || ps[2].R != 0 { + t.Errorf("bad or foreign fill must be black: %+v %+v", ps[1], ps[2]) + } + if got, _ := ParsePaths([]byte(``)) + f.Add([]byte(` p.X1 || p.Y0 > p.Y1 { + t.Fatalf("bad box %+v from %q", p, b) + } + } + // What the parser accepts the matcher must accept: no panic. + MatchPaths(ps, ps) + }) +} + +func TestParsePathsBoundsOnHugeInput(t *testing.T) { + var sb strings.Builder + for i := 0; i < 1000; i++ { + sb.WriteString(``) + } + ps, err := ParsePaths([]byte(sb.String())) + if err != nil || len(ps) != 1000 { + t.Fatalf("%v %d", err, len(ps)) + } +} diff --git a/internal/bench/tools.json b/internal/bench/tools.json new file mode 100644 index 0000000..01e027c --- /dev/null +++ b/internal/bench/tools.json @@ -0,0 +1,4 @@ +[ + {"name": "vtracer", "version": "VTracer 0.6.5", "source": "cargo install vtracer --version 0.6.5 --locked (crate vtracer, MIT)"}, + {"name": "resvg", "version": "0.50.0", "source": "cargo install resvg --version 0.50.0 --locked (crate resvg, MPL-2.0)"} +] diff --git a/internal/bench/variants.go b/internal/bench/variants.go new file mode 100644 index 0000000..f69f816 --- /dev/null +++ b/internal/bench/variants.go @@ -0,0 +1,41 @@ +package bench + +// Variant is one encoder setting or VTracer preset. +type Variant struct { + Label string + Family string // x264, x265, svtav1, vp9, vtracer + Args []string + Ext string // container of an encoder's output +} + +// Vector reports whether the variant is a vectorisation. +func (v Variant) Vector() bool { return v.Family == "vtracer" } + +// DefaultVariants are the settings of the 2026 study (rapport.md section 5), +// plus extra CRF points so that every VTracer result is bracketed by measured +// points of each codec on the rate-quality curve: matched-quality sizes are +// then interpolated between two measurements, not extrapolated. +func DefaultVariants() []Variant { + x264 := func(crf string) Variant { + return Variant{"x264 crf" + crf, "x264", []string{"-c:v", "libx264", "-preset", "slow", "-crf", crf}, "mp4"} + } + x265 := func(crf string) Variant { + return Variant{"x265 crf" + crf, "x265", []string{"-c:v", "libx265", "-preset", "slow", "-crf", crf}, "mp4"} + } + av1 := func(crf string) Variant { + return Variant{"svtav1 crf" + crf, "svtav1", []string{"-c:v", "libsvtav1", "-preset", "4", "-crf", crf}, "mkv"} + } + vp9 := func(crf string) Variant { + return Variant{"vp9 crf" + crf, "vp9", []string{"-c:v", "libvpx-vp9", "-b:v", "0", "-crf", crf, "-row-mt", "1"}, "webm"} + } + return []Variant{ + x264("18"), x264("23"), x264("30"), x264("40"), x264("51"), + x265("23"), x265("30"), x265("40"), x265("51"), + av1("30"), av1("45"), av1("60"), av1("63"), + vp9("32"), vp9("50"), vp9("63"), + {"vtracer default", "vtracer", nil, "svg"}, + {"vtracer poster", "vtracer", []string{"--preset", "poster"}, "svg"}, + {"vtracer photo", "vtracer", []string{"--preset", "photo"}, "svg"}, + {"vtracer coarse", "vtracer", []string{"-f", "16", "-p", "4", "-g", "64"}, "svg"}, + } +} diff --git a/internal/bench/y4m.go b/internal/bench/y4m.go new file mode 100644 index 0000000..120dc7a --- /dev/null +++ b/internal/bench/y4m.go @@ -0,0 +1,147 @@ +// Package bench holds the measurement code of vectorbench: clip download with +// SHA-256 checks, the ffmpeg and VTracer drivers, the parsers of their +// output, the matched-quality interpolation and the report. +package bench + +import ( + "bytes" + "errors" + "fmt" + "strconv" + "strings" +) + +// Limits on what a y4m header may claim. A header comes from a server, so a +// hostile one must not make us allocate or request an absurd prefix. +const ( + MaxDimension = 16384 + MaxHeaderLen = 4096 + maxPrefixSize = int64(1) << 36 // 64 GiB: a refusal bound, not a target +) + +// Y4M is what the header line of a YUV4MPEG2 stream says. +type Y4M struct { + Width, Height int + Chroma string // "420", "422", "444", "mono", with optional "p10" style depth suffix + FPSNum int + FPSDen int + HeaderLen int // bytes of the header line, including the newline +} + +// ParseY4MHeader reads the first line of a YUV4MPEG2 stream. data may hold +// more than the header; only the first line is read. +func ParseY4MHeader(data []byte) (Y4M, error) { + nl := bytes.IndexByte(data, '\n') + if nl < 0 { + if len(data) >= MaxHeaderLen { + return Y4M{}, errors.New("y4m: header line longer than the limit") + } + return Y4M{}, errors.New("y4m: no newline in the header") + } + if nl >= MaxHeaderLen { + return Y4M{}, errors.New("y4m: header line longer than the limit") + } + h := Y4M{Chroma: "420", HeaderLen: nl + 1, FPSNum: 0, FPSDen: 1} + fields := strings.Fields(string(data[:nl])) + if len(fields) == 0 || fields[0] != "YUV4MPEG2" { + return Y4M{}, errors.New("y4m: not a YUV4MPEG2 stream") + } + for _, f := range fields[1:] { + if f == "" { + continue + } + val := f[1:] + switch f[0] { + case 'W': + n, err := strconv.Atoi(val) + if err != nil || n <= 0 || n > MaxDimension { + return Y4M{}, fmt.Errorf("y4m: bad width %q", val) + } + h.Width = n + case 'H': + n, err := strconv.Atoi(val) + if err != nil || n <= 0 || n > MaxDimension { + return Y4M{}, fmt.Errorf("y4m: bad height %q", val) + } + h.Height = n + case 'C': + h.Chroma = val + case 'F': + num, den, ok := strings.Cut(val, ":") + a, e1 := strconv.Atoi(num) + b, e2 := strconv.Atoi(den) + if !ok || e1 != nil || e2 != nil || a < 0 || b <= 0 { + return Y4M{}, fmt.Errorf("y4m: bad frame rate %q", val) + } + h.FPSNum, h.FPSDen = a, b + } + } + if h.Width == 0 || h.Height == 0 { + return Y4M{}, errors.New("y4m: no width or height") + } + if _, err := h.FrameBytes(); err != nil { + return Y4M{}, err + } + return h, nil +} + +// FrameBytes is the size of one frame's pixel data, without the FRAME marker. +func (h Y4M) FrameBytes() (int64, error) { + c := h.Chroma + depth := int64(1) + // "p" at the end is a bit depth; the 'p' of "jpeg" or "paldv" is not. + if i := strings.LastIndexByte(c, 'p'); i > 0 && i+1 < len(c) && c[i+1] >= '0' && c[i+1] <= '9' { + bits, err := strconv.Atoi(c[i+1:]) + if err != nil || bits < 8 || bits > 16 { + return 0, fmt.Errorf("y4m: bad bit depth in chroma %q", c) + } + if bits > 8 { + depth = 2 + } + c = c[:i] + } + if strings.HasSuffix(c, "alpha") { + return 0, errors.New("y4m: alpha planes are not supported") + } + luma := int64(h.Width) * int64(h.Height) + var chroma int64 + switch c { + case "420", "420jpeg", "420mpeg2", "420paldv": + chroma = 2 * ((int64(h.Width) + 1) / 2) * ((int64(h.Height) + 1) / 2) + case "422": + chroma = 2 * ((int64(h.Width) + 1) / 2) * int64(h.Height) + case "444": + chroma = 2 * luma + case "mono": + chroma = 0 + default: + return 0, fmt.Errorf("y4m: unsupported chroma %q", h.Chroma) + } + return (luma + chroma) * depth, nil +} + +// PrefixLen is the byte length of the header plus the first n frames, each +// with its "FRAME\n" marker (frame parameters are not supported: a marker with +// parameters makes the prefix longer and the check fails loudly). +func (h Y4M) PrefixLen(n int) (int64, error) { + if n <= 0 { + return 0, errors.New("y4m: frame count must be positive") + } + fb, err := h.FrameBytes() + if err != nil { + return 0, err + } + total := int64(h.HeaderLen) + int64(n)*(fb+6) + if total <= 0 || total > maxPrefixSize { + return 0, errors.New("y4m: prefix too large") + } + return total, nil +} + +// FPS returns the frame rate as a float, 0 when the header gave none. +func (h Y4M) FPS() float64 { + if h.FPSDen == 0 { + return 0 + } + return float64(h.FPSNum) / float64(h.FPSDen) +} diff --git a/internal/bench/y4m_test.go b/internal/bench/y4m_test.go new file mode 100644 index 0000000..b4038f6 --- /dev/null +++ b/internal/bench/y4m_test.go @@ -0,0 +1,164 @@ +package bench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestParseY4MHeader(t *testing.T) { + line := "YUV4MPEG2 W1920 H1080 F24:1 Ip A1:1 C420jpeg XYSCSS=420JPEG\n" + h, err := ParseY4MHeader([]byte(line + "FRAME\n")) + if err != nil { + t.Fatal(err) + } + if h.Width != 1920 || h.Height != 1080 || h.FPS() != 24 || h.HeaderLen != len(line) { + t.Fatalf("%+v", h) + } + fb, _ := h.FrameBytes() + if fb != 1920*1080*3/2 { + t.Fatalf("frame bytes %d", fb) + } + p, err := h.PrefixLen(24) + if err != nil || p != int64(h.HeaderLen)+24*(fb+6) { + t.Fatalf("prefix %d %v", p, err) + } +} + +func TestY4MFrameSizes(t *testing.T) { + cases := map[string]int64{ + "422": 4 * 2 * 2, "444": 4 * 2 * 3, "mono": 8, + "420p10": 12 * 2, "444p12": 24 * 2, "420": 12, + } + for c, want := range cases { + h := Y4M{Width: 4, Height: 2, Chroma: c} + got, err := h.FrameBytes() + if err != nil || got != want { + t.Errorf("%s: %d %v, want %d", c, got, err, want) + } + } + // odd sizes round the chroma planes up + h := Y4M{Width: 5, Height: 3, Chroma: "420"} + if got, _ := h.FrameBytes(); got != 15+2*3*2 { + t.Errorf("odd 420: %d", got) + } +} + +func TestParseY4MHeaderRefusals(t *testing.T) { + bad := []string{ + "", "YUV4MPEG2 W16 H16", "MPEG W16 H16\n", "YUV4MPEG2 H16\n", "YUV4MPEG2 W0 H16\n", + "YUV4MPEG2 W99999 H16\n", "YUV4MPEG2 W16 H16 F0:0\n", "YUV4MPEG2 W16 H16 Cfoo\n", + "YUV4MPEG2 W16 H16 C420p99\n", "YUV4MPEG2 W16 H16 C420alpha\n", "YUV4MPEG2 W16 Hx\n", + "YUV4MPEG2 W16 H16 F:\n", + "YUV4MPEG2 " + strings.Repeat("W16 ", 2000) + "\n", + } + for _, s := range bad { + if _, err := ParseY4MHeader([]byte(s)); err == nil { + t.Errorf("accepted %.40q", s) + } + } + if _, err := (Y4M{Width: 16, Height: 16, Chroma: "420", HeaderLen: 10}).PrefixLen(0); err == nil { + t.Error("zero frames accepted") + } + if _, err := (Y4M{Width: MaxDimension, Height: MaxDimension, Chroma: "444p16", HeaderLen: 10}).PrefixLen(1 << 20); err == nil { + t.Error("absurd prefix accepted") + } +} + +func FuzzParseY4MHeader(f *testing.F) { + f.Add([]byte("YUV4MPEG2 W1920 H1080 F24:1 C420\n")) + f.Add([]byte("YUV4MPEG2 W2 H2 C444p10\nFRAME\n")) + f.Add([]byte{}) + f.Fuzz(func(t *testing.T, b []byte) { + h, err := ParseY4MHeader(b) + if err != nil { + return + } + if h.Width <= 0 || h.Height <= 0 || h.Width > MaxDimension || h.Height > MaxDimension || h.HeaderLen <= 0 || h.HeaderLen > len(b) { + t.Fatalf("accepted %+v", h) + } + if p, err := h.PrefixLen(24); err == nil && p <= 0 { + t.Fatalf("prefix %d", p) + } + }) +} + +// y4mFile builds a tiny stream of n frames of 4x2 4:2:0. +func y4mFile(n int) []byte { + b := []byte("YUV4MPEG2 W4 H2 F1:1 C420\n") + for i := 0; i < n; i++ { + b = append(b, "FRAME\n"...) + b = append(b, make([]byte, 12)...) + } + return b +} + +func TestFetchPrefixRange(t *testing.T) { + full := y4mFile(10) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.ServeContent(w, r, "x.y4m", time.Time{}, strings.NewReader(string(full))) + })) + defer srv.Close() + dest := filepath.Join(t.TempDir(), "d", "p.y4m") + got, err := FetchPrefix(context.Background(), srv.Client(), srv.URL, 3, dest) + if err != nil { + t.Fatal(err) + } + want := 26 + 3*18 + sum := sha256.Sum256(full[:want]) + if got != hex.EncodeToString(sum[:]) { + t.Fatal("hash differs from the first 3 frames") + } + if st, _ := os.Stat(dest); st.Size() != int64(want) { + t.Fatalf("size %d, want %d", st.Size(), want) + } + if err := VerifyPin("c", got, got); err != nil { + t.Fatal(err) + } + if err := VerifyPin("c", got, strings.Repeat("0", 64)); err == nil || !strings.Contains(err.Error(), "mismatch") { + t.Fatalf("mismatch not refused: %v", err) + } + if err := VerifyPin("c", got, ""); err == nil || !strings.Contains(err.Error(), got) { + t.Fatalf("missing pin not refused with the computed hash: %v", err) + } +} + +func TestFetchPrefixServerIgnoresRange(t *testing.T) { + full := y4mFile(10) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(full) })) + defer srv.Close() + dest := filepath.Join(t.TempDir(), "p.y4m") + if _, err := FetchPrefix(context.Background(), srv.Client(), srv.URL, 2, dest); err != nil { + t.Fatal(err) + } + if st, _ := os.Stat(dest); st.Size() != int64(26+2*18) { + t.Fatalf("kept %d bytes", st.Size()) + } +} + +func TestFetchPrefixFailures(t *testing.T) { + short := y4mFile(1) + cases := map[string]http.HandlerFunc{ + "truncated": func(w http.ResponseWriter, r *http.Request) { w.Write(short) }, + "404": func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }, + "not y4m": func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello\n")) }, + } + for name, h := range cases { + srv := httptest.NewServer(h) + dest := filepath.Join(t.TempDir(), "p.y4m") + if _, err := FetchPrefix(context.Background(), srv.Client(), srv.URL, 5, dest); err == nil { + t.Errorf("%s: no error", name) + } + if fileExists(dest) || fileExists(dest+".part") { + t.Errorf("%s: left a file behind", name) + } + srv.Close() + } +} diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..34041af --- /dev/null +++ b/renovate.json @@ -0,0 +1 @@ +{"extends": ["github>go-avkit/.github"]}