ws-video2: MPEG-2 field-picture / concealment-vector fixtures (a syntax-level writer in tools/fixtures/mpeg2.py), bit-exact; LuaJIT-friendlier hot paths; mpeg2 bench line

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 14:50:27 -05:00
1 parent f90fcbb029
commit 9444e83f45
4 files changed
+322 -18

No files matched your search

+17
View File
@@ -964,11 +964,28 @@ do
end
end
end
-- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2)
local M2 = require("@tests/gen/mpeg2_bench")
local function mpeg2(tag: string)
for _, s in M2 do
local file = Base64.decode(s.file) :: buffer
fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = false })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
jitTune(false)
mpeg1("")
mpeg2("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
mpeg2(" (jit tuned)")
jitTune(false)
end
end
+249 -3
View File
@@ -1,9 +1,11 @@
# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder
# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the
# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames) and from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures), each with `ffmpeg -idct int` decoding as the reference: the IJG integer
# IDCT that codecs/video/Dsp reproduces, so the planes must match exactly.
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second
# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors),
# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so
# the planes must match exactly.
# tests/gen/mpeg2_<name>.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64),
# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of
# every frame's cropped planes, display order), bands = { { crc } } (per frame, of
@@ -126,6 +128,14 @@ def generate(ctx):
% (dp, y4m)])
emit("dualprime", open(dp, "rb").read(), dp, 1)
# field pictures and concealment vectors (field_stream below: no encoder at hand writes them)
seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")]
for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)):
path = os.path.join(tmp, name + ".m2v")
es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal)
open(path, "wb").write(es)
emit(name, es, path, 1)
# the prog stream in the containers (stream copy)
prog = os.path.join(tmp, "prog.m2v")
cont = {"crcs": crcs["prog"]}
@@ -176,3 +186,239 @@ def zlib_crc32_mpeg(data):
for _ in range(8):
crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF
return crc
# ---------------------------------------------------------------------------------------------------------------------
# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field
# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in
# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse
# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is
# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here).
MBAI = {1: "1", 2: "011", 3: "010"}
DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]
DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]
# |motion_code| 0..16 (Table B-10), then the sign bit
MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001",
"0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"]
CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"}
MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"}
MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011",
"intra": "00011"}
class Bits:
def __init__(self):
self.s = []
def put(self, v, n):
self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "")
def code(self, c):
self.s.append(c)
def start(self, code):
# next_start_code: zero stuffing to a byte boundary, then 00 00 01 code
n = len("".join(self.s))
if n % 8:
self.s.append("0" * (8 - n % 8))
self.put(0x000001, 24)
self.put(code, 8)
def bytes(self):
s = "".join(self.s)
s += "0" * (-len(s) % 8)
return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8))
def field_stream(rng, w, h, frames, conceal=False):
"""frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]"""
b = Bits()
mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32)
fh = mbh * 8 # field height in lines (coded)
b.start(0xB3)
b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1)
b.put(0, 1), b.put(0, 1)
b.start(0xB5)
b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1)
b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5)
b.start(0xB8)
b.put(0, 25), b.put(1, 1), b.put(0, 1)
# temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded
# just before it)
tr, d, last_ref = {}, 0, None
for k, f in enumerate(frames):
if f[0] != "B":
if last_ref is not None:
tr[last_ref] = d
d += 1
last_ref = k
else:
tr[k] = d
d += 1
tr[last_ref] = d
for k, (t0, t1) in enumerate(frames):
for fi, ptype in enumerate((t0, t1)):
parity = fi # top field first
pt = {"I": 1, "P": 2, "B": 3}[ptype]
b.start(0x00)
b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16)
if pt >= 2:
b.put(0, 1), b.put(7, 3)
if pt == 3:
b.put(0, 1), b.put(7, 3)
b.put(0, 1)
b.start(0xB5)
fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15)
if pt == 1 and conceal:
fc = (1, 1, 15, 15)
b.put(8, 4)
for f in fc:
b.put(f, 4)
b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1)
b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1)
# the second field of the first frame has one reference: the first field (no skips, zero-vector or
# dual-prime prediction from its own parity)
only_first = k == 0 and fi == 1
for row in range(mbh // 2):
b.start(row + 1)
b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1)
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c]
dc = [128, 128, 128]
col = 0
prev_dirs = None
while col < mbw:
# B skips repeat the previous vectors: only after zero ones (they stay inside the picture)
skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and
prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1])))
if skip:
b.code(MBAI[2])
col += 1 # the skipped one
dc = [128, 128, 128]
if pt == 2:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
else:
b.code(MBAI[1])
if pt == 1 or rng.random() < 0.08:
b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"])
if conceal:
# field_select, a concealment vector (the predictor again: motion codes 0), marker
b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1)
pmv[0][2:] = pmv[0][:2]
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
for blk in range(6):
comp = 0 if blk < 4 else blk - 3
target = rng.randrange(40, 216)
diff = target - dc[comp]
dc[comp] = target
size = abs(diff).bit_length()
b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size])
if size:
b.put(diff if diff > 0 else diff + (1 << size) - 1, size)
ac_block(b, rng, 1, 0.5)
prev_dirs = None
col += 1
continue
dc = [128, 128, 128]
if pt == 2:
kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else
("mc", "mc_coded", "mc_coded", "nomc_coded", "mc"))
dirs = (0,) if kind != "nomc_coded" else ()
b.code(MBTYPE_P[kind])
coded = kind != "mc"
else:
kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded"))
dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,)
b.code(MBTYPE_B[kind])
coded = kind.endswith("coded")
if dirs:
choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else [])
mt = rng.choice(choices)
b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2)
for d in dirs:
motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None)
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
if coded:
cbp = rng.choice(list(CBP))
b.code(CBP[cbp])
for blk in range(6):
if cbp & (32 >> blk):
ac_block(b, rng, 0, 0.6)
prev_dirs = dirs
col += 1
b.start(0xB7)
return b.bytes()
def ac_block(b, rng, first, more):
# escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one
n = first
count = 0
while n < 64 and (count == 0 and first == 0 or rng.random() < more):
run = rng.randrange(0, 6)
if n + run > 63:
break
level = rng.choice((-1, 1)) * rng.randrange(1, 24)
b.code("000001"), b.put(run, 6), b.put(level, 12)
n += run + 1
count += 1
b.code("10")
def put_motion(b, delta):
b.code(MOTION[abs(delta)])
if delta:
b.put(1 if delta < 0 else 0, 1)
def wrap(v):
return (v + 16) % 32 - 16
def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel):
"""one direction's vectors for a field-picture macroblock, kept inside the reference field"""
def ok(mx, my, rows, y0):
sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1)
return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh
def pick(px, py, rows, y0, extra=None):
for _ in range(50):
mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11)
dx, dy = wrap(mx - px), wrap(my - py)
if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)):
return dx, dy, mx, my
return None
if mt == "field":
sel = rng.randrange(2) if force_sel is None else force_sel
r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
elif mt == "16x8":
for half in range(2):
sel = rng.randrange(2) if force_sel is None else force_sel
px, py = pmv[half * 2], pmv[half * 2 + 1]
r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1])
else:
# dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector
def dmv_ok(dmx, dmy):
def f(mx, my):
ox = ((mx + (mx > 0)) >> 1) + dmx
oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1)
return ok(ox, oy, 16, row * 16)
return f
for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7):
r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy))
if r:
break
assert r, "dual prime: no vector fits"
put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx])
put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]