Files
magpie/internal/h264/encode_test.go
T
yetone 81798f7793 browser: a recording is an MP4, encoded in magpie (GIF on format: gif)
record_stop now makes an H.264 MP4 by default, from the same frames as
the GIF (a second a frame, the last held three, the first frame's
size). record_stop takes format: "mp4" (default) or "gif"; any other
value is refused and the recording goes on, so the agent can ask again.

internal/h264 is a small encoder with no cgo and no ffmpeg:
Constrained Baseline, CAVLC, deblocking off. The first picture is IDR.
After that a macroblock the same as before is P_Skip, and a changed one
is Intra16x16 (V/H/DC by SAD). Colour is BT.709 limited range, and an
odd size is cropped. The MP4 puts its moov before mdat, so a player can
start before it has the whole file. QP 23.

The image MCP's file route serves through http.ServeContent, so a
player's Range request gets 206. Safari plays an MP4 only when it is
served that way. extOf gives video/mp4 the extension .mp4.

Run (on mote unless named):
- internal/h264 TestDecodersMakeTheSamePicture. ffmpeg n7.1 (local;
  mote has none) decodes 7 cases to the encoder's own reconstruction,
  byte for byte (diff 0): 330x190 q24, 800x522 q20, 64x48 q10,
  48x32 q40, 96x64 q0 (escape codes), 96x64 q51, 18x18 q23.
  TestEncodeKeepsThePicture: PSNR 42-44 dB at q24.
- internal/gateway: TestBrowserMP4, TestBrowserGIF*,
  TestBrowserRecordStopWithNothing, TestBrowserToolListIsSmall
  (4585 bytes vs 12138), TestImageMCP*.
- TestBrowserRecordsAVideo, in a real Chrome for Testing (chromium-1234)
  with the extension: the MP4 has video/mp4 and a .mp4 link, and a Range
  request gets 206. Chrome opens the link and plays it: 800 wide, 5 s,
  a frame read back from a canvas. format gif decodes to 3 frames, and
  format webm is refused.
- All of internal/gateway's Browser and ImageMCP tests on origin/main
  3fc6ee411, green. The 3-frame recording was MP4 24 KB, GIF 26 KB.
- go vet for darwin, linux and windows; gofmt -l clean.

Broken by hand:
- w.Write in place of ServeContent: TestBrowserRecordsAVideo is red
  ("a range: 200").
- avcC's NAL length size changed from 4 to 2: Chrome's playback check is
  red (this change also stops the script waiting more than 10 s).
- Before the fix in this change, a non-symmetric Hadamard gave PSNR
  ~20 dB and an ffmpeg mismatch. Both tests were red.

Not tried: Safari or Firefox playback, a Windows or Linux run of the
real-browser test, or a recording of hundreds of frames for time and
size.
2026-11-09 06:03:39 +08:00

179 lines
5.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package h264
import (
"bytes"
"encoding/binary"
"image"
"image/color"
"image/draw"
"math"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strconv"
"testing"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
)
// screens are pictures like a recording's: text, flat colour, a photo-like
// gradient with noise, and from one to the next a few things change.
func screens(w, h, n int) []*image.RGBA {
rnd := rand.New(rand.NewPCG(1, 2))
var out []*image.RGBA
base := image.NewRGBA(image.Rect(0, 0, w, h))
draw.Draw(base, base.Bounds(), image.White, image.Point{}, draw.Src)
for y := h / 2; y < h; y++ {
for x := 0; x < w/3; x++ {
base.Set(x, y, color.RGBA{uint8(x * 255 / (w / 3)), uint8(y * 255 / h), uint8(rnd.IntN(256)), 255})
}
}
draw.Draw(base, image.Rect(w/2, 10, w-10, 60), image.NewUniform(color.RGBA{0x1d, 0x9b, 0xf0, 255}), image.Point{}, draw.Src)
for i := range n {
img := image.NewRGBA(base.Bounds())
copy(img.Pix, base.Pix)
d := font.Drawer{Dst: img, Src: image.NewUniform(color.RGBA{0x20, 0x20, 0x20, 255}), Face: basicfont.Face7x13}
for l := 0; l <= i && l < 20; l++ {
d.Dot = fixed.P(12, 20+l*16)
d.DrawString("The quick brown fox jumps over the lazy dog, line " + string(rune('a'+l)))
}
if i%3 == 1 { // a box that comes and goes
draw.Draw(img, image.Rect(w/2+i*7, h/2, w/2+i*7+90, h/2+40), image.NewUniform(color.RGBA{0xe0, 0x30, 0x40, 255}), image.Point{}, draw.Src)
}
if i == n-2 { // a picture just like the one before it
copy(img.Pix, out[len(out)-1].Pix)
}
out = append(out, img)
}
return out
}
// recon is the encoder's last picture as decoded, w×h, as yuv420p.
func recon(e *Encoder) []byte {
var b []byte
W := e.mbw * 16
for y := range e.h {
b = append(b, e.ref.y[y*W:y*W+e.w]...)
}
for _, p := range [][]byte{e.ref.cb, e.ref.cr} {
for y := range e.h / 2 {
b = append(b, p[y*W/2:y*W/2+e.w/2]...)
}
}
return b
}
func encodeScreens(t *testing.T, w, h, qp, n int) (*Encoder, [][]byte, []planes) {
t.Helper()
e, err := NewEncoder(w, h, qp)
if err != nil {
t.Fatal(err)
}
var recs [][]byte
var srcs []planes
for i, img := range screens(w, h, n) {
ms := 1000
if i == n-1 {
ms = 3000
}
e.Add(img, ms)
recs = append(recs, recon(e))
srcs = append(srcs, e.prev)
}
return e, recs, srcs
}
// TestEncodeKeepsThePicture: what a decoder makes of each picture is near
// its source (PSNR over 36 dB in luma).
func TestEncodeKeepsThePicture(t *testing.T) {
for _, qp := range []int{18, 24, 30} {
e, recs, srcs := encodeScreens(t, 330, 190, qp, 6)
for i := range recs {
W := e.mbw * 16
var se float64
for y := range e.h {
for x := range e.w {
d := float64(recs[i][y*e.w+x]) - float64(srcs[i].y[y*W+x])
se += d * d
}
}
psnr := 10 * math.Log10(255*255/(se/float64(e.w*e.h)+1e-9))
if psnr < 36 {
t.Errorf("qp %d picture %d: PSNR %.1f dB", qp, i, psnr)
}
t.Logf("qp %d picture %d: PSNR %.1f dB", qp, i, psnr)
}
t.Logf("qp %d: %d bytes", qp, len(e.MP4()))
}
}
// TestDecodersMakeTheSamePicture: ffmpeg decodes the video to exactly the
// pictures the encoder predicted from. Any difference would drift from
// picture to picture.
func TestDecodersMakeTheSamePicture(t *testing.T) {
dump := os.Getenv("H264_DUMP")
ff, err := exec.LookPath("ffmpeg")
if err != nil && dump == "" {
t.Skip("no ffmpeg")
}
for _, c := range []struct{ w, h, qp int }{{330, 190, 24}, {800, 522, 20}, {64, 48, 10}, {48, 32, 40}, {96, 64, 0}, {96, 64, 51}, {18, 18, 23}} {
e, recs, _ := encodeScreens(t, c.w, c.h, c.qp, 7)
mp4 := e.MP4()
want := bytes.Join(recs, nil)
dir := t.TempDir()
if dump != "" {
dir = filepath.Join(dump, filepath.Base(t.Name())+"-"+itoa(c.w)+"x"+itoa(c.h)+"-"+itoa(c.qp))
os.MkdirAll(dir, 0o755)
os.WriteFile(filepath.Join(dir, "want.yuv"), want, 0o644)
}
f := filepath.Join(dir, "v.mp4")
os.WriteFile(f, mp4, 0o644)
if ff == "" {
continue
}
got, err := exec.Command(ff, "-v", "error", "-i", f, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-").Output()
if err != nil {
t.Fatalf("%dx%d: ffmpeg: %v", c.w, c.h, err)
}
if !bytes.Equal(got, want) {
fs := len(want) / len(recs)
for i := 0; i*fs < min(len(got), len(want)); i++ {
if !bytes.Equal(got[i*fs:min(len(got), (i+1)*fs)], want[i*fs:(i+1)*fs]) {
t.Fatalf("%dx%d qp %d: picture %d decodes otherwise (got %d bytes, want %d)", c.w, c.h, c.qp, i, len(got), len(want))
}
}
t.Fatalf("%dx%d: got %d bytes, want %d", c.w, c.h, len(got), len(want))
}
}
}
func itoa(n int) string { return strconv.Itoa(n) }
// TestMP4Boxes: the file is ftyp, moov, then mdat, each box's size its own
// and the chunk offset where the first picture starts.
func TestMP4Boxes(t *testing.T) {
e, _, _ := encodeScreens(t, 100, 60, 26, 4)
f := e.MP4()
var types []string
off := 0
for off < len(f) {
n := int(binary.BigEndian.Uint32(f[off:]))
types = append(types, string(f[off+4:off+8]))
if n < 8 || off+n > len(f) {
t.Fatalf("box %s at %d: size %d", f[off+4:off+8], off, n)
}
off += n
}
if want := []string{"ftyp", "moov", "mdat"}; len(types) != 3 || types[0] != want[0] || types[1] != want[1] || types[2] != want[2] {
t.Fatalf("boxes %v, want %v", types, want)
}
i := bytes.Index(f, []byte("stco"))
chunk := int(binary.BigEndian.Uint32(f[i+12:]))
if l := int(binary.BigEndian.Uint32(f[chunk:])); l != len(e.samples[0])-4 {
t.Fatalf("stco points at a %d-byte unit, the first picture is %d", l, len(e.samples[0])-4)
}
}