diff --git a/internal/gateway/browser.go b/internal/gateway/browser.go index 935d6b808..3b4507db0 100644 --- a/internal/gateway/browser.go +++ b/internal/gateway/browser.go @@ -572,7 +572,8 @@ func (s *Server) browserMCPCall(r *http.Request, m mcpMessage) (any, map[string] } json.Unmarshal(p.Arguments, &acted) if tool == browserRecordTool { - return s.browserRecord(r, browserSession(r), acted["action"] == "record_stop"), nil + format, _ := acted["format"].(string) + return s.browserRecord(r, browserSession(r), acted["action"] == "record_stop", format), nil } p.Name, p.Arguments, shot = tool, args, wants } else if !browserToolNamed(p.Name) { diff --git a/internal/gateway/browser_one.go b/internal/gateway/browser_one.go index 806ce4150..519d8ca46 100644 --- a/internal/gateway/browser_one.go +++ b/internal/gateway/browser_one.go @@ -80,7 +80,7 @@ func browserOneTool() map[string]any { "snapshot [interactive, ref, maxChars]: the page as an accessibility tree, a ref on each element you can act on.\n" + "click [ref, double, button, modifiers]. type [ref, text, clear, submit, slowly]. press [key, ref]. hover [ref]. select [ref, values]. scroll [direction, amount, ref]. drag [from, to]. upload [ref, paths].\n" + "wait [text, textGone, url, seconds, timeout]. screenshot [ref, fullPage, png]. evaluate [script, ref]. text [maxChars]: the visible text. console [level, limit]. dialog [accept, promptText].\n" + - "record_start: keep a picture of the window after each action that changes the page. record_stop: those pictures as a GIF, at a link to download, for the user to see what was done.\n" + + "record_start: keep a picture of the window after each action that changes the page. record_stop [format]: those pictures as a video, at a link to download, for the user to see what was done.\n" + "Every action takes tab, and screenshot: true to add a small picture of the window to its answer.", "inputSchema": map[string]any{ "type": "object", @@ -117,6 +117,7 @@ func browserOneTool() map[string]any { "limit": num("console: the most recent messages."), "accept": boolean("dialog: accept (default true) or dismiss."), "promptText": str("dialog: a prompt's answer."), + "format": map[string]any{"type": "string", "enum": []string{"mp4", "gif"}, "description": "record_stop: mp4 (default) or gif."}, "screenshot": boolean("Add a small picture of the window to the answer."), }, "required": []string{"action"}, diff --git a/internal/gateway/browser_record.go b/internal/gateway/browser_record.go index 48bfb59cd..fcc1d2d96 100644 --- a/internal/gateway/browser_record.go +++ b/internal/gateway/browser_record.go @@ -16,13 +16,15 @@ import ( "time" "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/h264" "golang.org/x/image/draw" "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/math/fixed" ) -// A recording is a GIF of what an agent did in its tab: between the +// A recording is a video (MP4, or a GIF when asked) of what an agent did in +// its tab: between the // browser tool's record_start and record_stop, the gateway takes a picture // of the window after each action that can change the page, with the // action written under it. The gateway does it all, so any extension @@ -176,6 +178,44 @@ func browserRecFrame(data, label string) ([]byte, error) { return out.Bytes(), nil } +// browserRecQP is the MP4's quantizer: small text stays sharp (about 43 dB +// on a page of text) at a fraction of the GIF's size. +const browserRecQP = 23 + +// browserMP4 is frames as an H.264 MP4: a second a frame, the last held +// three, every frame the first one's size. +func browserMP4(frames [][]byte) ([]byte, error) { + var e *h264.Encoder + var size image.Rectangle + for i, f := range frames { + img, err := jpeg.Decode(bytes.NewReader(f)) + if err != nil { + return nil, err + } + b := img.Bounds() + if e == nil { + size = image.Rect(0, 0, b.Dx(), b.Dy()) + if e, err = h264.NewEncoder(b.Dx(), b.Dy(), browserRecQP); err != nil { + return nil, err + } + } else if b.Dx() != size.Dx() || b.Dy() != size.Dy() { + // a window resized: every frame is the first one's size + dst := image.NewRGBA(size) + draw.ApproxBiLinear.Scale(dst, size, img, b, draw.Src, nil) + img = dst + } + ms := 1000 + if i == len(frames)-1 { + ms = 3000 + } + e.Add(img, ms) + } + if e == nil { + return nil, errors.New("no frames") + } + return e.MP4(), nil +} + // browserGIF is frames as an animated GIF: a second a frame, the last held // three. Each frame after the first holds only the rectangle that changed. func browserGIF(frames [][]byte) ([]byte, error) { @@ -271,11 +311,20 @@ func changed(a, b *image.Paletted) image.Rectangle { return image.Rect(x0, y0, x1, y1) } -// browserRecord answers record_start and record_stop. -func (s *Server) browserRecord(r *http.Request, session string, stop bool) map[string]any { +// browserRecord answers record_start and record_stop; format is stop's +// "gif" or "mp4" (the default). +func (s *Server) browserRecord(r *http.Request, session string, stop bool, format string) map[string]any { if !stop { s.browser.recs.start(session) - return toolResult("Recording. After each action that can change the page a picture of the window is kept, with the action under it; record_stop makes them a GIF.", false) + return toolResult("Recording. After each action that can change the page a picture of the window is kept, with the action under it; record_stop makes them a video.", false) + } + name, mt, encode := "MP4", "video/mp4", browserMP4 + switch format { + case "", "mp4": + case "gif": + name, mt, encode = "GIF", "image/gif", browserGIF + default: + return toolResult("record_stop's format is mp4 or gif.", true) } rec := s.browser.recs.stop(session) if rec == nil { @@ -284,14 +333,14 @@ func (s *Server) browserRecord(r *http.Request, session string, stop bool) map[s if len(rec.frames) == 0 { return toolResult("The recording has no frames: no action that changes the page was taken after record_start.", true) } - data, err := browserGIF(rec.frames) + data, err := encode(rec.frames) if err != nil { - return toolResult("The GIF couldn't be made: "+err.Error(), true) + return toolResult("The "+name+" couldn't be made: "+err.Error(), true) } - u := imageMCPBase(r) + ImageMCPFiles + s.imageMCPKeepFile(data, "image/gif", access.Caller(r.Context()).KeyID) + u := imageMCPBase(r) + ImageMCPFiles + s.imageMCPKeepFile(data, mt, access.Caller(r.Context()).KeyID) var b strings.Builder - fmt.Fprintf(&b, "Recorded %d frames over %s, a %d KB GIF. Download it within the hour (the link opens without a header; whoever has it can open it), e.g. curl -o recording.gif '%s'\n%s\n", - len(rec.frames), time.Since(rec.started).Round(time.Second), (len(data)+1023)/1024, u, u) + fmt.Fprintf(&b, "Recorded %d frames over %s, a %d KB %s. Download it within the hour (the link opens without a header; whoever has it can open it), e.g. curl -o recording%s '%s'\n%s\n", + len(rec.frames), time.Since(rec.started).Round(time.Second), (len(data)+1023)/1024, name, extOf(mt), u, u) if rec.full { fmt.Fprintf(&b, "It holds the first %d frames; later actions weren't kept.\n", browserRecMost) } diff --git a/internal/gateway/browser_record_test.go b/internal/gateway/browser_record_test.go index d658d1ad5..eec539a43 100644 --- a/internal/gateway/browser_record_test.go +++ b/internal/gateway/browser_record_test.go @@ -3,6 +3,7 @@ package gateway import ( "bytes" "encoding/json" + "fmt" "image" "image/color" "image/gif" @@ -61,6 +62,40 @@ func TestBrowserGIFFramesHoldWhatChanged(t *testing.T) { } } +// A recording's MP4 has a frame an action, held a second, the last three, +// every frame the first one's size, its index before its pictures. +func TestBrowserMP4(t *testing.T) { + frames := [][]byte{ + recJPEG(t, 400, 301, image.Rectangle{}), + recJPEG(t, 400, 301, image.Rect(100, 100, 160, 140)), + recJPEG(t, 400, 301, image.Rect(100, 100, 160, 140)), + recJPEG(t, 800, 600, image.Rectangle{}), // a resized window + } + data, err := browserMP4(frames) + if err != nil { + t.Fatal(err) + } + if string(data[4:8]) != "ftyp" || bytes.Index(data, []byte("moov")) > bytes.Index(data, []byte("mdat")) { + t.Fatalf("starts %q: not ftyp, moov, mdat", data[:16]) + } + i := bytes.Index(data, []byte("stts")) + if i < 0 { + t.Fatal("no stts") + } + // version/flags, 2 runs: 3 a second, 1 three seconds + want := []byte{0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0x03, 0xe8, 0, 0, 0, 1, 0, 0, 0x0b, 0xb8} + if got := data[i+4 : i+4+len(want)]; !bytes.Equal(got, want) { + t.Fatalf("stts % x", got) + } + i = bytes.Index(data, []byte("stsd")) + bytes.Index(data[bytes.Index(data, []byte("stsd")):], []byte("avc1")) + if w, h := int(data[i+28])<<8|int(data[i+29]), int(data[i+30])<<8|int(data[i+31]); w != 400 || h != 302 { + t.Fatalf("avc1 %dx%d, want 400x302 (cropped to 301)", w, h) + } + if _, err := browserMP4(nil); err == nil { + t.Fatal("no frames made an MP4") + } +} + // A frame's label says what was done to what, never what was typed. func TestBrowserRecSayKeepsTypedTextOut(t *testing.T) { got := browserRecSay(3, "type", map[string]any{"ref": "e4", "text": "hunter2", "action": "type"}) @@ -92,36 +127,87 @@ func TestBrowserRecordStopWithNothing(t *testing.T) { } // Recording in a real Chromium: the actions that change the page are each -// a frame of the GIF at the answer's link, the ones that read it are not. -func TestBrowserRecordsAGIF(t *testing.T) { +// a frame of the MP4 at the answer's link, which Chromium plays; the ones +// that read it are not. format: gif makes a GIF instead. +func TestBrowserRecordsAVideo(t *testing.T) { srv, site := realBrowser(t) call, ok := browserCaller(t, srv, "rec") - ok("browser", map[string]any{"action": "record_start"}, "Recording") - page := ok("browser", map[string]any{"action": "navigate", "url": site.URL}, "Magpie fixture") - name := regexp.MustCompile(`textbox "Name"[^\n]*\[ref=(e\d+)\]`).FindStringSubmatch(page) - if name == nil { - t.Fatalf("no Name field in:\n%s", page) + record := func(format string) (string, []byte, string) { + t.Helper() + ok("browser", map[string]any{"action": "record_start"}, "Recording") + page := ok("browser", map[string]any{"action": "navigate", "url": site.URL}, "Magpie fixture") + name := regexp.MustCompile(`textbox "Name"[^\n]*\[ref=(e\d+)\]`).FindStringSubmatch(page) + if name == nil { + t.Fatalf("no Name field in:\n%s", page) + } + ok("browser", map[string]any{"action": "type", "ref": name[1], "text": "hunter2"}) + ok("browser", map[string]any{"action": "snapshot"}) + ok("browser", map[string]any{"action": "navigate", "url": site.URL + "/two"}, "Page two") + args := map[string]any{"action": "record_stop"} + if format != "" { + args["format"] = format + } + m := call("browser", args) + if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Recorded 3 frames") { + t.Fatalf("%+v", m.Result) + } + var files []MadeFile + if json.Unmarshal([]byte(m.meta(FilesMeta)), &files) != nil || len(files) != 1 { + t.Fatalf("files %s", m.meta(FilesMeta)) + } + resp, err := http.Get(files[0].URL) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + return files[0].URL, b, resp.Header.Get("Content-Type") } - ok("browser", map[string]any{"action": "type", "ref": name[1], "text": "hunter2"}) - ok("browser", map[string]any{"action": "snapshot"}) - ok("browser", map[string]any{"action": "navigate", "url": site.URL + "/two"}, "Page two") - m := call("browser", map[string]any{"action": "record_stop"}) - if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Recorded 3 frames") { - t.Fatalf("%+v", m.Result) + + u, b, mt := record("") + if mt != "video/mp4" || len(b) < 8 || string(b[4:8]) != "ftyp" { + t.Fatalf("%s, starts %q", mt, b[:min(len(b), 16)]) } - var files []MadeFile - if json.Unmarshal([]byte(m.meta(FilesMeta)), &files) != nil || len(files) != 1 { - t.Fatalf("files %s", m.meta(FilesMeta)) + if !strings.Contains(u, ".mp4?") { + t.Fatalf("the link %s doesn't end .mp4", u) } - resp, err := http.Get(files[0].URL) + // a player asks for ranges + req, _ := http.NewRequest("GET", u, nil) + req.Header.Set("Range", "bytes=0-99") + resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } - b, _ := io.ReadAll(resp.Body) + part, _ := io.ReadAll(resp.Body) resp.Body.Close() + if resp.StatusCode != http.StatusPartialContent || !bytes.Equal(part, b[:100]) { + t.Fatalf("a range: %d, %d bytes", resp.StatusCode, len(part)) + } + // Chromium plays it: three frames over five seconds, browserRecWidth + // wide, and a picture that isn't black + // (opened as its own page, so its picture can be read) + ok("browser", map[string]any{"action": "navigate", "url": u}) + play := `async () => { + const v = document.querySelector('video'); + v.muted = true; + if (v.readyState < 2) await new Promise((ok, no) => { v.onloadeddata = ok; v.onerror = () => no(new Error('video error ' + (v.error && v.error.code))); setTimeout(() => no(new Error('not loaded: readyState ' + v.readyState)), 10000); }); + const c = document.createElement('canvas'); + c.width = v.videoWidth; c.height = v.videoHeight; + const g = c.getContext('2d'); + g.drawImage(v, 0, 0); + const d = g.getImageData(0, 0, c.width, c.height).data; + let lit = 0; + for (let i = 0; i < d.length; i += 4) if (d[i] + d[i+1] + d[i+2] > 600) lit++; + return 'played ' + v.videoWidth + ' ' + v.duration + ' ' + (lit > d.length / 40); + }` + ok("browser", map[string]any{"action": "evaluate", "script": play}, fmt.Sprintf("played %d 5 true", browserRecWidth)) + + mp4 := len(b) + _, b, mt = record("gif") + t.Logf("MP4 %d KB, GIF %d KB", mp4/1024, len(b)/1024) g, err := gif.DecodeAll(bytes.NewReader(b)) if err != nil { - t.Fatalf("%d %s: %v", resp.StatusCode, resp.Header.Get("Content-Type"), err) + t.Fatalf("%s: %v", mt, err) } if len(g.Image) != 3 || g.Config.Width != browserRecWidth { t.Fatalf("%d frames, %d wide", len(g.Image), g.Config.Width) @@ -129,4 +215,8 @@ func TestBrowserRecordsAGIF(t *testing.T) { if m := call("browser", map[string]any{"action": "record_stop"}); !m.Result.IsError { t.Fatalf("a second stop: %+v", m.Result) } + ok("browser", map[string]any{"action": "record_start"}, "Recording") + if m := call("browser", map[string]any{"action": "record_stop", "format": "webm"}); !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "mp4 or gif") { + t.Fatalf("format webm: %+v", m.Result) + } } diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 5665ef317..187161dd9 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -1913,6 +1913,9 @@ func extOf(mimeType string) string { return ".webp" case "image/gif": return ".gif" + case "video/mp4": + // a browser recording + return ".mp4" case "image/svg+xml": // Recraft's vector models at OpenRouter return ".svg" diff --git a/internal/gateway/image_mcp.go b/internal/gateway/image_mcp.go index 2faedefa4..92f7aa18d 100644 --- a/internal/gateway/image_mcp.go +++ b/internal/gateway/image_mcp.go @@ -750,11 +750,9 @@ func (s *Server) imageMCPFile(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", f.mime) w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Cache-Control", "private, max-age=3600") - w.Header().Set("Content-Length", strconv.Itoa(len(f.data))) - if r.Method == http.MethodHead { - return - } - w.Write(f.data) + // ranges, which a player asks a video in (Safari only plays an MP4 + // served so) + http.ServeContent(w, r, "", f.made, bytes.NewReader(f.data)) } // imageMCPBase is the address the agent reaches the gateway at, for the diff --git a/internal/h264/bits.go b/internal/h264/bits.go new file mode 100644 index 000000000..5f11af361 --- /dev/null +++ b/internal/h264/bits.go @@ -0,0 +1,79 @@ +package h264 + +// bits writes a bit string, most significant bit first. +type bits struct { + buf []byte + acc uint64 + n uint // bits in acc not yet in buf, fewer than 8 +} + +// u writes v's low n bits, n ≤ 32. +func (w *bits) u(n uint, v uint32) { + if n == 0 { + return + } + w.acc = w.acc<= 8 { + w.n -= 8 + w.buf = append(w.buf, byte(w.acc>>w.n)) + } +} + +func (w *bits) flag(b bool) { + if b { + w.u(1, 1) + } else { + w.u(1, 0) + } +} + +// ue writes v as Exp-Golomb. +func (w *bits) ue(v uint32) { + x := uint64(v) + 1 + n := uint(0) + for x>>n > 1 { + n++ + } + w.u(n, 0) + w.u(n+1, uint32(x)) +} + +// se writes v as signed Exp-Golomb. +func (w *bits) se(v int32) { + if v > 0 { + w.ue(uint32(2*v - 1)) + } else { + w.ue(uint32(-2 * v)) + } +} + +// trailing ends an RBSP: a one, then zeros to the byte. +func (w *bits) trailing() []byte { + w.u(1, 1) + if w.n > 0 { + w.u(8-w.n, 0) + } + return w.buf +} + +// nal is an RBSP as a NAL unit: its header, then the payload with an +// emulation-prevention byte wherever two zeros meet a byte under four. +func nal(refIdc, typ byte, rbsp []byte) []byte { + out := make([]byte, 0, len(rbsp)+len(rbsp)/64+2) + out = append(out, refIdc<<5|typ) + zeros := 0 + for _, b := range rbsp { + if zeros >= 2 && b <= 3 { + out = append(out, 3) + zeros = 0 + } + out = append(out, b) + if b == 0 { + zeros++ + } else { + zeros = 0 + } + } + return out +} diff --git a/internal/h264/encode.go b/internal/h264/encode.go new file mode 100644 index 000000000..815b96804 --- /dev/null +++ b/internal/h264/encode.go @@ -0,0 +1,835 @@ +// Package h264 makes small H.264 videos of screen pictures, in pure Go: +// Constrained Baseline, every changed macroblock coded Intra 16x16 with +// CAVLC, every unchanged one skipped. It is built for a series of +// screenshots shown a second each, where most of a picture stays as it +// was, not for camera video. +package h264 + +import ( + "errors" + "image" + "image/draw" +) + +// An Encoder takes pictures of one size, each with how long it is shown, +// and makes them a video. +type Encoder struct { + w, h int // the size shown, even + mbw, mbh int // in macroblocks + qp int + level int + + ref, cur, prev planes // the last picture as decoded, this one, the last source + n int // pictures encoded + tcY []uint8 + tcC [2][]uint8 + + samples [][]byte // each picture's NAL units, each after its 4-byte length + ms []uint32 +} + +// planes is a picture as 4:2:0 YCbCr, padded to whole macroblocks. +type planes struct{ y, cb, cr []byte } + +// NewEncoder is an encoder of w×h pictures at quantiser qp (0–51; lower is +// sharper and bigger). +func NewEncoder(w, h, qp int) (*Encoder, error) { + if w <= 0 || h <= 0 { + return nil, errors.New("h264: an empty picture") + } + if qp < 0 || qp > 51 { + return nil, errors.New("h264: qp is 0 to 51") + } + w, h = (w+1)&^1, (h+1)&^1 + e := &Encoder{w: w, h: h, mbw: (w + 15) / 16, mbh: (h + 15) / 16, qp: qp} + fs := e.mbw * e.mbh + for _, l := range []struct{ idc, fs int }{{31, 3600}, {32, 5120}, {40, 8192}, {42, 8704}, {50, 22080}, {51, 36864}} { + if fs <= l.fs && e.mbw*e.mbw <= 8*l.fs && e.mbh*e.mbh <= 8*l.fs { + e.level = l.idc + break + } + } + if e.level == 0 { + return nil, errors.New("h264: the picture is too big") + } + e.ref, e.cur = e.newPlanes(), e.newPlanes() + e.tcY = make([]uint8, fs*16) + e.tcC = [2][]uint8{make([]uint8, fs*4), make([]uint8, fs*4)} + return e, nil +} + +func (e *Encoder) newPlanes() planes { + n := e.mbw * e.mbh * 256 + return planes{make([]byte, n), make([]byte, n/4), make([]byte, n/4)} +} + +// Add encodes img, shown for ms milliseconds. A picture of another size +// is cut or padded at its right and bottom. +func (e *Encoder) Add(img image.Image, ms int) { + src := e.convert(img) + e.encode(src) + e.prev = src + e.ms = append(e.ms, uint32(max(ms, 1))) +} + +// convert is img as BT.709 limited-range YCbCr, the edge repeated into the +// padding. +func (e *Encoder) convert(img image.Image) planes { + b := img.Bounds() + rgba, ok := img.(*image.RGBA) + if !ok { + rgba = image.NewRGBA(b) + draw.Draw(rgba, b, img, b.Min, draw.Src) + } + p := e.newPlanes() + W, H := e.mbw*16, e.mbh*16 + lw, lh := min(e.w, b.Dx()), min(e.h, b.Dy()) + if lw == 0 || lh == 0 { + for i := range p.y { + p.y[i] = 16 + } + for i := range p.cb { + p.cb[i], p.cr[i] = 128, 128 + } + return p + } + at := func(x, y int) (int32, int32, int32) { + o := rgba.PixOffset(b.Min.X+min(x, lw-1), b.Min.Y+min(y, lh-1)) + return int32(rgba.Pix[o]), int32(rgba.Pix[o+1]), int32(rgba.Pix[o+2]) + } + for y := 0; y < H; y += 2 { + for x := 0; x < W; x += 2 { + var sr, sg, sb int32 + for k := range 4 { + px, py := x+k&1, y+k>>1 + r, g, bl := at(px, py) + p.y[py*W+px] = uint8((47*r+157*g+16*bl+128)>>8 + 16) + sr, sg, sb = sr+r, sg+g, sb+bl + } + c := (y/2)*(W/2) + x/2 + p.cb[c] = uint8(clamp((-26*sr-86*sg+112*sb+512)>>10 + 128)) + p.cr[c] = uint8(clamp((112*sr-102*sg-10*sb+512)>>10 + 128)) + } + } + return p +} + +func clamp(v int32) int32 { + if v < 0 { + return 0 + } + if v > 255 { + return 255 + } + return v +} + +// encode codes src as the next picture: the first as an IDR picture, each +// later one as a P picture whose unchanged macroblocks are skipped. +func (e *Encoder) encode(src planes) { + idr := e.n == 0 + var w bits + w.ue(0) // first_mb_in_slice + if idr { + w.ue(7) // I + } else { + w.ue(5) // P + } + w.ue(0) // pic_parameter_set_id + w.u(16, uint32(e.n&0xffff)) // frame_num + if idr { + w.ue(0) // idr_pic_id + } else { + w.u(1, 0) // num_ref_idx_active_override_flag + w.u(1, 0) // ref_pic_list_modification_flag_l0 + } + if idr { + w.u(1, 0) // no_output_of_prior_pics_flag + w.u(1, 0) // long_term_reference_flag + } else { + w.u(1, 0) // adaptive_ref_pic_marking_mode_flag + } + w.se(int32(e.qp - 26)) // slice_qp_delta + w.ue(1) // disable_deblocking_filter_idc + + skip := 0 + for my := range e.mbh { + for mx := range e.mbw { + if !idr && e.same(src, mx, my) { + skip++ + e.copyRef(mx, my) + e.setTC(mx, my, nil, nil) + continue + } + if !idr { + w.ue(uint32(skip)) + skip = 0 + } + e.intra(&w, src, mx, my, !idr) + } + } + if skip > 0 { + w.ue(uint32(skip)) + } + rbsp := w.trailing() + unit := nal(2, 1, rbsp) + if idr { + unit = nal(3, 5, rbsp) + } + s := make([]byte, 4, 4+len(unit)) + s[0], s[1], s[2], s[3] = byte(len(unit)>>24), byte(len(unit)>>16), byte(len(unit)>>8), byte(len(unit)) + e.samples = append(e.samples, append(s, unit...)) + e.ref, e.cur = e.cur, e.ref + e.n++ +} + +// same reports whether macroblock (mx, my) of src is as it was in the +// last source picture. +func (e *Encoder) same(src planes, mx, my int) bool { + W := e.mbw * 16 + for y := my * 16; y < my*16+16; y++ { + o := y*W + mx*16 + if string(src.y[o:o+16]) != string(e.prev.y[o:o+16]) { + return false + } + } + for y := my * 8; y < my*8+8; y++ { + o := y*W/2 + mx*8 + if string(src.cb[o:o+8]) != string(e.prev.cb[o:o+8]) || string(src.cr[o:o+8]) != string(e.prev.cr[o:o+8]) { + return false + } + } + return true +} + +// copyRef is a skipped macroblock: the last picture's, unmoved. +func (e *Encoder) copyRef(mx, my int) { + W := e.mbw * 16 + for y := my * 16; y < my*16+16; y++ { + o := y*W + mx*16 + copy(e.cur.y[o:o+16], e.ref.y[o:o+16]) + } + for y := my * 8; y < my*8+8; y++ { + o := y*W/2 + mx*8 + copy(e.cur.cb[o:o+8], e.ref.cb[o:o+8]) + copy(e.cur.cr[o:o+8], e.ref.cr[o:o+8]) + } +} + +// setTC records the TotalCoeff of each 4x4 block of macroblock (mx, my), +// for later blocks' nC; nil is none coded. +func (e *Encoder) setTC(mx, my int, y *[16]uint8, c *[2][4]uint8) { + gw := e.mbw * 4 + for b := range 16 { + v := uint8(0) + if y != nil { + v = y[b] + } + e.tcY[(my*4+b>>2)*gw+mx*4+b&3] = v + } + cw := e.mbw * 2 + for k := range 2 { + for b := range 4 { + v := uint8(0) + if c != nil { + v = c[k][b] + } + e.tcC[k][(my*2+b>>1)*cw+mx*2+b&1] = v + } + } +} + +// nC is the predicted TotalCoeff of the 4x4 block at (x, y) of grid g, +// gw blocks wide, from its left and upper neighbours. +func nC(g []uint8, gw, x, y int) int { + a, b := x > 0, y > 0 + switch { + case a && b: + return (int(g[y*gw+x-1]) + int(g[(y-1)*gw+x]) + 1) >> 1 + case a: + return int(g[y*gw+x-1]) + case b: + return int(g[(y-1)*gw+x]) + } + return 0 +} + +// pred16 is Intra 16x16 prediction of the block at (x0, y0) of plane p +// (stride s), in mode 0 (vertical), 1 (horizontal) or 2 (DC). +func pred16(p []byte, s, x0, y0, mode int, left, top bool, out *[256]int32) { + switch mode { + case 0: + for y := range 16 { + for x := range 16 { + out[y*16+x] = int32(p[(y0-1)*s+x0+x]) + } + } + case 1: + for y := range 16 { + v := int32(p[(y0+y)*s+x0-1]) + for x := range 16 { + out[y*16+x] = v + } + } + default: + var sum, n int32 + if top { + for x := range 16 { + sum += int32(p[(y0-1)*s+x0+x]) + } + n += 16 + } + if left { + for y := range 16 { + sum += int32(p[(y0+y)*s+x0-1]) + } + n += 16 + } + v := int32(128) + if n > 0 { + v = (sum + n/2) / n + } + for i := range out { + out[i] = v + } + } +} + +// pred8 is chroma prediction of the 8x8 block at (x0, y0), in mode 0 (DC), +// 1 (horizontal) or 2 (vertical). +func pred8(p []byte, s, x0, y0, mode int, left, top bool, out *[64]int32) { + switch mode { + case 1: + for y := range 8 { + v := int32(p[(y0+y)*s+x0-1]) + for x := range 8 { + out[y*8+x] = v + } + } + case 2: + for y := range 8 { + for x := range 8 { + out[y*8+x] = int32(p[(y0-1)*s+x0+x]) + } + } + default: + for b := range 4 { + xo, yo := (b&1)*4, (b>>1)*4 + var st, sl int32 + if top { + for x := range 4 { + st += int32(p[(y0-1)*s+x0+xo+x]) + } + } + if left { + for y := range 4 { + sl += int32(p[(y0+yo+y)*s+x0-1]) + } + } + v := int32(128) + switch { + case xo > 0 && yo == 0: // the upper right block leans on the row above + if top { + v = (st + 2) >> 2 + } else if left { + v = (sl + 2) >> 2 + } + case xo == 0 && yo > 0: // the lower left one on the column at its left + if left { + v = (sl + 2) >> 2 + } else if top { + v = (st + 2) >> 2 + } + default: + switch { + case top && left: + v = (st + sl + 4) >> 3 + case left: + v = (sl + 2) >> 2 + case top: + v = (st + 2) >> 2 + } + } + for y := range 4 { + for x := range 4 { + out[(yo+y)*8+xo+x] = v + } + } + } + } +} + +// fdct is the forward 4x4 core transform, in place, raster order. +func fdct(d *[16]int32) { + for i := range 4 { + r := d[i*4 : i*4+4] + s03, d03, s12, d12 := r[0]+r[3], r[0]-r[3], r[1]+r[2], r[1]-r[2] + r[0], r[1], r[2], r[3] = s03+s12, 2*d03+d12, s03-s12, d03-2*d12 + } + for j := range 4 { + s03, d03 := d[j]+d[12+j], d[j]-d[12+j] + s12, d12 := d[4+j]+d[8+j], d[4+j]-d[8+j] + d[j], d[4+j], d[8+j], d[12+j] = s03+s12, 2*d03+d12, s03-s12, d03-2*d12 + } +} + +// idct is §8.5.12.2: rows, then columns, then (x+32)>>6. +func idct(d *[16]int32) { + for i := range 4 { + r := d[i*4 : i*4+4] + e0, e1, e2, e3 := r[0]+r[2], r[0]-r[2], (r[1]>>1)-r[3], r[1]+(r[3]>>1) + r[0], r[1], r[2], r[3] = e0+e3, e1+e2, e1-e2, e0-e3 + } + for j := range 4 { + f0, f1, f2, f3 := d[j], d[4+j], d[8+j], d[12+j] + g0, g1, g2, g3 := f0+f2, f0-f2, (f1>>1)-f3, f1+(f3>>1) + d[j], d[4+j], d[8+j], d[12+j] = g0+g3, g1+g2, g1-g2, g0-g3 + } + for i := range d { + d[i] = (d[i] + 32) >> 6 + } +} + +// hadamard4 is H·c·H for the 4x4 luma DC, exact; H is symmetric, rows +// 1111, 11-1-1, 1-1-11, 1-11-1. +func hadamard4(c *[16]int32) { + for i := range 4 { + r := c[i*4 : i*4+4] + a, b, cc, d := r[0]+r[1], r[0]-r[1], r[2]+r[3], r[2]-r[3] + r[0], r[1], r[2], r[3] = a+cc, a-cc, b-d, b+d + } + for j := range 4 { + a, b := c[j]+c[4+j], c[j]-c[4+j] + cc, d := c[8+j]+c[12+j], c[8+j]-c[12+j] + c[j], c[4+j], c[8+j], c[12+j] = a+cc, a-cc, b-d, b+d + } +} + +// most bounds a level so that CAVLC's 12-bit escape can carry it. +const most = 2000 + +func quant(w, mf int32, qbits uint, f int64) int32 { + neg := w < 0 + if neg { + w = -w + } + z := int32((int64(w)*int64(mf) + f) >> qbits) + z = min(z, most) + if neg { + return -z + } + return z +} + +// scaleAC is §8.5.12.1 for a coefficient other than a DC. +func scaleAC(c int32, qp, pos int) int32 { + ls := 16 * normAdjust[qp%6][posClass(pos)] + if qp >= 24 { + return c * ls << (qp/6 - 4) + } + return (c*ls + 1<<(3-qp/6)) >> (4 - qp/6) +} + +func sad(a, b []int32) int32 { + var s int32 + for i := range a { + d := a[i] - b[i] + if d < 0 { + d = -d + } + s += d + } + return s +} + +// intra codes macroblock (mx, my) as Intra 16x16 and writes its +// reconstruction into e.cur. +func (e *Encoder) intra(w *bits, src planes, mx, my int, inP bool) { + S := e.mbw * 16 + x0, y0 := mx*16, my*16 + left, top := mx > 0, my > 0 + + // luma: the prediction nearest the source + var orig [256]int32 + for y := range 16 { + for x := range 16 { + orig[y*16+x] = int32(src.y[(y0+y)*S+x0+x]) + } + } + var pred, try [256]int32 + modeY, best := 2, int32(-1) + for _, m := range []int{2, 0, 1} { + if m == 0 && !top || m == 1 && !left { + continue + } + pred16(e.cur.y, S, x0, y0, m, left, top, &try) + if s := sad(orig[:], try[:]); best < 0 || s < best { + modeY, best, pred = m, s, try + } + } + + qp := e.qp + qbits := uint(15 + qp/6) + f := int64(1<>2 + var d [16]int32 + for y := range 4 { + for x := range 4 { + i := (by*4+y)*16 + bx*4 + x + d[y*4+x] = orig[i] - pred[i] + } + } + fdct(&d) + dc[b] = d[0] + for k := 1; k < 16; k++ { + pos := zigzag[k] + ac[b][k-1] = quant(d[pos], quantMF[qp%6][posClass(pos)], qbits, f) + anyAC = anyAC || ac[b][k-1] != 0 + } + } + hadamard4(&dc) + var dcLev [16]int32 + for i := range dc { + dcLev[i] = quant(dc[i]/2, quantMF[qp%6][0], qbits+1, 2*f) + } + cbpL := 0 + if anyAC { + cbpL = 15 + } else { + ac = [16][15]int32{} + } + + // luma reconstruction, as a decoder makes it + dcY := dcLev + hadamard4(&dcY) + ls := 16 * normAdjust[qp%6][0] + for i := range dcY { + if qp >= 36 { + dcY[i] = dcY[i] * ls << (qp/6 - 6) + } else { + dcY[i] = (dcY[i]*ls + 1<<(5-qp/6)) >> (6 - qp/6) + } + } + for b := range 16 { + bx, by := b&3, b>>2 + var d [16]int32 + d[0] = dcY[b] + for k := 1; k < 16; k++ { + d[zigzag[k]] = scaleAC(ac[b][k-1], qp, zigzag[k]) + } + idct(&d) + for y := range 4 { + for x := range 4 { + i := (by*4+y)*16 + bx*4 + x + e.cur.y[(y0+by*4+y)*S+x0+bx*4+x] = uint8(clamp(pred[i] + d[y*4+x])) + } + } + } + + // chroma + C := S / 2 + cx, cy := mx*8, my*8 + var corig [2][64]int32 + for k, pl := range [2][]byte{src.cb, src.cr} { + for y := range 8 { + for x := range 8 { + corig[k][y*8+x] = int32(pl[(cy+y)*C+cx+x]) + } + } + } + var cpred [2][64]int32 + modeC, bestC := 0, -1 + for _, m := range []int{0, 1, 2} { + if m == 2 && !top || m == 1 && !left { + continue + } + var t [2][64]int32 + pred8(e.cur.cb, C, cx, cy, m, left, top, &t[0]) + pred8(e.cur.cr, C, cx, cy, m, left, top, &t[1]) + if s := int(sad(corig[0][:], t[0][:]) + sad(corig[1][:], t[1][:])); bestC < 0 || s < bestC { + modeC, bestC, cpred = m, s, t + } + } + qpc := qpChroma(qp) + cbits := uint(15 + qpc/6) + cf := int64(1<>1 + var d [16]int32 + for y := range 4 { + for x := range 4 { + i := (by*4+y)*8 + bx*4 + x + d[y*4+x] = corig[k][i] - cpred[k][i] + } + } + fdct(&d) + c[b] = d[0] + for j := 1; j < 16; j++ { + pos := zigzag[j] + cac[k][b][j-1] = quant(d[pos], quantMF[qpc%6][posClass(pos)], cbits, cf) + anyCAC = anyCAC || cac[k][b][j-1] != 0 + } + } + h := [4]int32{c[0] + c[1] + c[2] + c[3], c[0] - c[1] + c[2] - c[3], c[0] + c[1] - c[2] - c[3], c[0] - c[1] - c[2] + c[3]} + for b := range 4 { + cdc[k][b] = quant(h[b], quantMF[qpc%6][0], cbits+1, 2*cf) + anyCDC = anyCDC || cdc[k][b] != 0 + } + } + cbpC := 0 + switch { + case anyCAC: + cbpC = 2 + case anyCDC: + cbpC = 1 + } + if cbpC < 2 { + cac = [2][4][15]int32{} + } + cls := 16 * normAdjust[qpc%6][0] + for k, pl := range [2][]byte{e.cur.cb, e.cur.cr} { + c := cdc[k] + h := [4]int32{c[0] + c[1] + c[2] + c[3], c[0] - c[1] + c[2] - c[3], c[0] + c[1] - c[2] - c[3], c[0] - c[1] - c[2] + c[3]} + for b := range 4 { + bx, by := b&1, b>>1 + var d [16]int32 + d[0] = (h[b] * cls << (qpc / 6)) >> 5 + for j := 1; j < 16; j++ { + d[zigzag[j]] = scaleAC(cac[k][b][j-1], qpc, zigzag[j]) + } + idct(&d) + for y := range 4 { + for x := range 4 { + i := (by*4+y)*8 + bx*4 + x + pl[(cy+by*4+y)*C+cx+bx*4+x] = uint8(clamp(cpred[k][i] + d[y*4+x])) + } + } + } + } + + // the macroblock's syntax + mbType := 1 + modeY + 4*cbpC + if cbpL != 0 { + mbType += 12 + } + if inP { + mbType += 5 + } + w.ue(uint32(mbType)) + w.ue(uint32(modeC)) // intra_chroma_pred_mode + w.se(0) // mb_qp_delta + gw := e.mbw * 4 + var dcScan [16]int32 + for k := range 16 { + dcScan[k] = dcLev[zigzag[k]] + } + w.residual(dcScan[:], nC(e.tcY, gw, mx*4, my*4)) + var tcY [16]uint8 + var tcC [2][4]uint8 + e.setTC(mx, my, &tcY, &tcC) // none yet: later blocks see only earlier ones + if cbpL != 0 { + for i := range 16 { // in decoding order: by 8x8 quadrant + bx := (i>>2&1)*2 + i&1 + by := (i>>3&1)*2 + i>>1&1 + gx, gy := mx*4+bx, my*4+by + tc := w.residual(ac[by*4+bx][:], nC(e.tcY, gw, gx, gy)) + e.tcY[gy*gw+gx] = uint8(tc) + } + } + if cbpC > 0 { + w.residual(cdc[0][:], -1) + w.residual(cdc[1][:], -1) + } + if cbpC == 2 { + cw := e.mbw * 2 + for k := range 2 { + for b := range 4 { + gx, gy := mx*2+b&1, my*2+b>>1 + tc := w.residual(cac[k][b][:], nC(e.tcC[k], cw, gx, gy)) + e.tcC[k][gy*cw+gx] = uint8(tc) + } + } + } +} + +// residual writes a block's coefficients, in scan order, with CAVLC +// (§9.2) at nC (-1 for chroma DC), and is its TotalCoeff. +func (w *bits) residual(coef []int32, nc int) int { + maxNum := len(coef) + var lv [16]int32 + var pos [16]int + total := 0 + for i := maxNum - 1; i >= 0; i-- { + if coef[i] != 0 { + lv[total], pos[total] = coef[i], i + total++ + } + } + t1 := 0 + for t1 < total && t1 < 3 && (lv[t1] == 1 || lv[t1] == -1) { + t1++ + } + if nc == -1 { + i := total*4 + t1 + w.u(uint(chromaDCTokenLen[i]), uint32(chromaDCTokenBits[i])) + } else { + t := 3 + switch { + case nc < 2: + t = 0 + case nc < 4: + t = 1 + case nc < 8: + t = 2 + } + i := total*4 + t1 + w.u(uint(coeffTokenLen[t][i]), uint32(coeffTokenBits[t][i])) + } + if total == 0 { + return 0 + } + suffix := uint(0) + if total > 10 && t1 < 3 { + suffix = 1 + } + for i := range total { + l := lv[i] + if i < t1 { + w.flag(l < 0) + continue + } + code := 2*l - 2 + if l < 0 { + code = -2*l - 1 + } + if i == t1 && t1 < 3 { + code -= 2 + } + switch { + case suffix == 0 && code < 14: + w.u(uint(code), 0) + w.u(1, 1) + case suffix == 0 && code < 30: + w.u(14, 0) + w.u(1, 1) + w.u(4, uint32(code-14)) + case suffix == 0: + w.u(15, 0) + w.u(1, 1) + w.u(12, uint32(code-30)) + case code>>suffix < 15: + w.u(uint(code>>suffix), 0) + w.u(1, 1) + w.u(suffix, uint32(code)) + default: + w.u(15, 0) + w.u(1, 1) + w.u(12, uint32(code-15< 3<<(suffix-1) && suffix < 6 { + suffix++ + } + } + if total < maxNum { + tz := pos[0] + 1 - total + if maxNum == 4 { + w.u(uint(chromaDCZerosLen[total-1][tz]), uint32(chromaDCZerosBits[total-1][tz])) + } else { + w.u(uint(totalZerosLen[total-1][tz]), uint32(totalZerosBits[total-1][tz])) + } + left := tz + for i := 0; i < total-1 && left > 0; i++ { + run := pos[i] - pos[i+1] - 1 + t := min(left, 7) - 1 + w.u(uint(runLen[t][run]), uint32(runBits[t][run])) + left -= run + } + } + return total +} + +// sps is the sequence parameter set's RBSP. +func (e *Encoder) sps() []byte { + var w bits + w.u(8, 66) // profile_idc: Baseline + w.u(8, 0xc0) // constraint_set0 and set1: Constrained Baseline + w.u(8, uint32(e.level)) + w.ue(0) // seq_parameter_set_id + w.ue(12) // log2_max_frame_num_minus4: 16 bits + w.ue(2) // pic_order_cnt_type: in decoding order + w.ue(1) // max_num_ref_frames + w.u(1, 0) + w.ue(uint32(e.mbw - 1)) + w.ue(uint32(e.mbh - 1)) + w.u(1, 1) // frame_mbs_only_flag + w.u(1, 1) // direct_8x8_inference_flag + cr, cb := (e.mbw*16-e.w)/2, (e.mbh*16-e.h)/2 + w.flag(cr > 0 || cb > 0) + if cr > 0 || cb > 0 { + w.ue(0) + w.ue(uint32(cr)) + w.ue(0) + w.ue(uint32(cb)) + } + w.u(1, 1) // vui_parameters_present_flag + w.u(1, 0) // aspect_ratio_info_present_flag + w.u(1, 0) // overscan_info_present_flag + w.u(1, 1) // video_signal_type_present_flag + w.u(3, 5) // video_format: unspecified + w.u(1, 0) // video_full_range_flag + w.u(1, 1) // colour_description_present_flag + w.u(8, 1) // BT.709 primaries, + w.u(8, 1) // transfer + w.u(8, 1) // and matrix + w.u(1, 0) // chroma_loc_info_present_flag + w.u(1, 0) // timing_info_present_flag + w.u(1, 0) // nal_hrd_parameters_present_flag + w.u(1, 0) // vcl_hrd_parameters_present_flag + w.u(1, 0) // pic_struct_present_flag + w.u(1, 1) // bitstream_restriction_flag + w.u(1, 1) // motion_vectors_over_pic_boundaries_flag + w.ue(0) // max_bytes_per_pic_denom + w.ue(0) // max_bits_per_mb_denom + w.ue(15) // log2_max_mv_length_horizontal + w.ue(15) // log2_max_mv_length_vertical + w.ue(0) // max_num_reorder_frames: each picture shows when decoded + w.ue(1) // max_dec_frame_buffering + return nal(3, 7, w.trailing()) +} + +// pps is the picture parameter set. +func (e *Encoder) pps() []byte { + var w bits + w.ue(0) // pic_parameter_set_id + w.ue(0) // seq_parameter_set_id + w.u(1, 0) // CAVLC + w.u(1, 0) // bottom_field_pic_order_in_frame_present_flag + w.ue(0) // num_slice_groups_minus1 + w.ue(0) // num_ref_idx_l0_default_active_minus1 + w.ue(0) // num_ref_idx_l1_default_active_minus1 + w.u(1, 0) // weighted_pred_flag + w.u(2, 0) // weighted_bipred_idc + w.se(0) // pic_init_qp_minus26 + w.se(0) // pic_init_qs_minus26 + w.se(0) // chroma_qp_index_offset + w.u(1, 1) // deblocking_filter_control_present_flag + w.u(1, 0) // constrained_intra_pred_flag + w.u(1, 0) // redundant_pic_cnt_present_flag + return nal(3, 8, w.trailing()) +} diff --git a/internal/h264/encode_test.go b/internal/h264/encode_test.go new file mode 100644 index 000000000..38fdcf0d6 --- /dev/null +++ b/internal/h264/encode_test.go @@ -0,0 +1,178 @@ +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) + } +} diff --git a/internal/h264/mp4.go b/internal/h264/mp4.go new file mode 100644 index 000000000..7f4dd3ce1 --- /dev/null +++ b/internal/h264/mp4.go @@ -0,0 +1,103 @@ +package h264 + +import "encoding/binary" + +// MP4 is the pictures added so far as an MP4 file, its index first so a +// player can start before the whole file is read. +func (e *Encoder) MP4() []byte { + var total uint64 + for _, d := range e.ms { + total += uint64(d) + } + sps, pps := e.sps(), e.pps() + ftyp := box("ftyp", []byte("isom"), u32(512), []byte("isomiso2avc1mp41")) + + var stts []byte + runs := 0 + for i := 0; i < len(e.ms); { + j := i + for j < len(e.ms) && e.ms[j] == e.ms[i] { + j++ + } + stts = append(stts, u32(uint32(j-i))...) + stts = append(stts, u32(e.ms[i])...) + runs++ + i = j + } + sizes := make([]byte, 0, 4*len(e.samples)) + var mdatLen uint64 + for _, s := range e.samples { + sizes = append(sizes, u32(uint32(len(s)))...) + mdatLen += uint64(len(s)) + } + avcC := box("avcC", []byte{1, 66, 0xc0, byte(e.level), 0xff, 0xe1}, + u16(uint16(len(sps))), sps, []byte{1}, u16(uint16(len(pps))), pps) + avc1 := box("avc1", make([]byte, 6), u16(1), make([]byte, 16), + u16(uint16(e.w)), u16(uint16(e.h)), u32(0x00480000), u32(0x00480000), u32(0), + u16(1), make([]byte, 32), u16(0x18), u16(0xffff), avcC) + moov := func(chunk uint32) []byte { + stbl := box("stbl", + full("stsd", 0, 0, u32(1), avc1), + full("stts", 0, 0, u32(uint32(runs)), stts), + full("stss", 0, 0, u32(1), u32(1)), + full("stsc", 0, 0, u32(1), u32(1), u32(uint32(len(e.samples))), u32(1)), + full("stsz", 0, 0, u32(0), u32(uint32(len(e.samples))), sizes), + full("stco", 0, 0, u32(1), u32(chunk))) + minf := box("minf", + full("vmhd", 0, 1, make([]byte, 8)), + box("dinf", full("dref", 0, 0, u32(1), full("url ", 0, 1))), + stbl) + mdia := box("mdia", + full("mdhd", 0, 0, u32(0), u32(0), u32(1000), u32(uint32(total)), u16(0x55c4), u16(0)), + full("hdlr", 0, 0, u32(0), []byte("vide"), make([]byte, 12), []byte("VideoHandler\x00")), + minf) + tkhd := full("tkhd", 0, 3, u32(0), u32(0), u32(1), u32(0), u32(uint32(total)), + make([]byte, 8), u16(0), u16(0), u16(0), u16(0), matrix(), + u32(uint32(e.w)<<16), u32(uint32(e.h)<<16)) + mvhd := full("mvhd", 0, 0, u32(0), u32(0), u32(1000), u32(uint32(total)), + u32(0x00010000), u16(0x0100), make([]byte, 10), matrix(), make([]byte, 24), u32(2)) + return box("moov", mvhd, box("trak", tkhd, mdia)) + } + head := len(ftyp) + len(moov(0)) + 8 + out := make([]byte, 0, uint64(head)+mdatLen) + out = append(out, ftyp...) + out = append(out, moov(uint32(head))...) + out = append(out, u32(uint32(8+mdatLen))...) + out = append(out, "mdat"...) + for _, s := range e.samples { + out = append(out, s...) + } + return out +} + +func u32(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) } +func u16(v uint16) []byte { return binary.BigEndian.AppendUint16(nil, v) } + +func box(typ string, parts ...[]byte) []byte { + n := 8 + for _, p := range parts { + n += len(p) + } + out := make([]byte, 0, n) + out = binary.BigEndian.AppendUint32(out, uint32(n)) + out = append(out, typ...) + for _, p := range parts { + out = append(out, p...) + } + return out +} + +// full is a full box: its version and flags before its parts. +func full(typ string, version byte, flags uint32, parts ...[]byte) []byte { + vf := u32(uint32(version)<<24 | flags) + return box(typ, append([][]byte{vf}, parts...)...) +} + +// matrix is the identity transformation. +func matrix() []byte { + var m []byte + for _, v := range []uint32{0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000} { + m = append(m, u32(v)...) + } + return m +} diff --git a/internal/h264/tables.go b/internal/h264/tables.go new file mode 100644 index 000000000..eaeb6bf0d --- /dev/null +++ b/internal/h264/tables.go @@ -0,0 +1,196 @@ +package h264 + +// The CAVLC code tables of ITU-T H.264 §9.2 (Tables 9-5, 9-7, 9-8, 9-9 and +// 9-10), as code lengths and code values. + +// coeffTokenLen and coeffTokenBits are coeff_token for 0≤nC<2, 2≤nC<4, +// 4≤nC<8 and 8≤nC, at [TotalCoeff*4+TrailingOnes]. +var coeffTokenLen = [4][4 * 17]uint8{ + { + 1, 0, 0, 0, + 6, 2, 0, 0, 8, 6, 3, 0, 9, 8, 7, 5, 10, 9, 8, 6, + 11, 10, 9, 7, 13, 11, 10, 8, 13, 13, 11, 9, 13, 13, 13, 10, + 14, 14, 13, 11, 14, 14, 14, 13, 15, 15, 14, 14, 15, 15, 15, 14, + 16, 15, 15, 15, 16, 16, 16, 15, 16, 16, 16, 16, 16, 16, 16, 16, + }, + { + 2, 0, 0, 0, + 6, 2, 0, 0, 6, 5, 3, 0, 7, 6, 6, 4, 8, 6, 6, 4, + 8, 7, 7, 5, 9, 8, 8, 6, 11, 9, 9, 6, 11, 11, 11, 7, + 12, 11, 11, 9, 12, 12, 12, 11, 12, 12, 12, 11, 13, 13, 13, 12, + 13, 13, 13, 13, 13, 14, 13, 13, 14, 14, 14, 13, 14, 14, 14, 14, + }, + { + 4, 0, 0, 0, + 6, 4, 0, 0, 6, 5, 4, 0, 6, 5, 5, 4, 7, 5, 5, 4, + 7, 5, 5, 4, 7, 6, 6, 4, 7, 6, 6, 4, 8, 7, 7, 5, + 8, 8, 7, 6, 9, 8, 8, 7, 9, 9, 8, 8, 9, 9, 9, 8, + 10, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + }, + { + 6, 0, 0, 0, + 6, 6, 0, 0, 6, 6, 6, 0, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + }, +} + +var coeffTokenBits = [4][4 * 17]uint8{ + { + 1, 0, 0, 0, + 5, 1, 0, 0, 7, 4, 1, 0, 7, 6, 5, 3, 7, 6, 5, 3, + 7, 6, 5, 4, 15, 6, 5, 4, 11, 14, 5, 4, 8, 10, 13, 4, + 15, 14, 9, 4, 11, 10, 13, 12, 15, 14, 9, 12, 11, 10, 13, 8, + 15, 1, 9, 12, 11, 14, 13, 8, 7, 10, 9, 12, 4, 6, 5, 8, + }, + { + 3, 0, 0, 0, + 11, 2, 0, 0, 7, 7, 3, 0, 7, 10, 9, 5, 7, 6, 5, 4, + 4, 6, 5, 6, 7, 6, 5, 8, 15, 6, 5, 4, 11, 14, 13, 4, + 15, 10, 9, 4, 11, 14, 13, 12, 8, 10, 9, 8, 15, 14, 13, 12, + 11, 10, 9, 12, 7, 11, 6, 8, 9, 8, 10, 1, 7, 6, 5, 4, + }, + { + 15, 0, 0, 0, + 15, 14, 0, 0, 11, 15, 13, 0, 8, 12, 14, 12, 15, 10, 11, 11, + 11, 8, 9, 10, 9, 14, 13, 9, 8, 10, 9, 8, 15, 14, 13, 13, + 11, 14, 10, 12, 15, 10, 13, 12, 11, 14, 9, 12, 8, 10, 13, 8, + 13, 7, 9, 12, 9, 12, 11, 10, 5, 8, 7, 6, 1, 4, 3, 2, + }, + { + 3, 0, 0, 0, + 0, 1, 0, 0, 4, 5, 6, 0, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + }, +} + +// chromaDCTokenLen and chromaDCTokenBits are coeff_token for nC = -1. +var chromaDCTokenLen = [4 * 5]uint8{ + 2, 0, 0, 0, + 6, 1, 0, 0, + 6, 6, 3, 0, + 6, 7, 7, 6, + 6, 8, 8, 7, +} + +var chromaDCTokenBits = [4 * 5]uint8{ + 1, 0, 0, 0, + 7, 1, 0, 0, + 4, 6, 1, 0, + 3, 3, 2, 5, + 2, 3, 2, 0, +} + +// totalZerosLen and totalZerosBits are total_zeros of a 4x4 block, at +// [TotalCoeff-1][total_zeros]. +var totalZerosLen = [15][16]uint8{ + {1, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9}, + {3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6}, + {4, 3, 3, 3, 4, 4, 3, 3, 4, 5, 5, 6, 5, 6}, + {5, 3, 4, 4, 3, 3, 3, 4, 3, 4, 5, 5, 5}, + {4, 4, 4, 3, 3, 3, 3, 3, 4, 5, 4, 5}, + {6, 5, 3, 3, 3, 3, 3, 3, 4, 3, 6}, + {6, 5, 3, 3, 3, 2, 3, 4, 3, 6}, + {6, 4, 5, 3, 2, 2, 3, 3, 6}, + {6, 6, 4, 2, 2, 3, 2, 5}, + {5, 5, 3, 2, 2, 2, 4}, + {4, 4, 3, 3, 1, 3}, + {4, 4, 2, 1, 3}, + {3, 3, 1, 2}, + {2, 2, 1}, + {1, 1}, +} + +var totalZerosBits = [15][16]uint8{ + {1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 1}, + {7, 6, 5, 4, 3, 5, 4, 3, 2, 3, 2, 3, 2, 1, 0}, + {5, 7, 6, 5, 4, 3, 4, 3, 2, 3, 2, 1, 1, 0}, + {3, 7, 5, 4, 6, 5, 4, 3, 3, 2, 2, 1, 0}, + {5, 4, 3, 7, 6, 5, 4, 3, 2, 1, 1, 0}, + {1, 1, 7, 6, 5, 4, 3, 2, 1, 1, 0}, + {1, 1, 5, 4, 3, 3, 2, 1, 1, 0}, + {1, 1, 1, 3, 3, 2, 2, 1, 0}, + {1, 0, 1, 3, 2, 1, 1, 1}, + {1, 0, 1, 3, 2, 1, 1}, + {0, 1, 1, 2, 1, 3}, + {0, 1, 1, 1, 1}, + {0, 1, 1, 1}, + {0, 1, 1}, + {0, 1}, +} + +// chromaDCZerosLen and chromaDCZerosBits are total_zeros of a chroma DC +// block. +var chromaDCZerosLen = [3][4]uint8{ + {1, 2, 3, 3}, + {1, 2, 2, 0}, + {1, 1, 0, 0}, +} + +var chromaDCZerosBits = [3][4]uint8{ + {1, 1, 1, 0}, + {1, 1, 0, 0}, + {1, 0, 0, 0}, +} + +// runLen and runBits are run_before, at [min(zerosLeft,7)-1][run_before]. +var runLen = [7][15]uint8{ + {1, 1}, + {1, 2, 2}, + {2, 2, 2, 2}, + {2, 2, 2, 3, 3}, + {2, 2, 3, 3, 3, 3}, + {2, 3, 3, 3, 3, 3, 3}, + {3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11}, +} + +var runBits = [7][15]uint8{ + {1, 0}, + {1, 1, 0}, + {3, 2, 1, 0}, + {3, 2, 1, 1, 0}, + {3, 2, 3, 2, 1, 0}, + {3, 0, 1, 3, 2, 5, 4}, + {7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1}, +} + +// zigzag is the 4x4 frame scan: scan position → raster position +// (row*4+column). +var zigzag = [16]int{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15} + +// normAdjust is v of §8.5.9: for qP%6, a position with both coordinates +// even, both odd, or one of each. +var normAdjust = [6][3]int32{ + {10, 16, 13}, {11, 18, 14}, {13, 20, 16}, {14, 23, 18}, {16, 25, 20}, {18, 29, 23}, +} + +// quantMF is the encoder's multiplier, matched to normAdjust. +var quantMF = [6][3]int32{ + {13107, 5243, 8066}, {11916, 4660, 7490}, {10082, 4194, 6554}, + {9362, 3647, 5825}, {8192, 3355, 5243}, {7282, 2893, 4559}, +} + +// posClass is a raster position's column in normAdjust and quantMF. +func posClass(pos int) int { + r, c := pos>>2, pos&3 + switch { + case r&1 == 0 && c&1 == 0: + return 0 + case r&1 == 1 && c&1 == 1: + return 1 + } + return 2 +} + +// chromaQP is QPc for qPI ≥ 30 (Table 8-15). +var chromaQP = [22]int{29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39} + +func qpChroma(qp int) int { + if qp < 30 { + return qp + } + return chromaQP[qp-30] +}