Files
magpie/internal/h264/mp4.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

104 lines
3.3 KiB
Go

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
}