From 9444e83f4590e9e2ceaf1820beaf0ea3c61edde3 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:50:27 -0500 Subject: [PATCH] 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 --- src/Formats/codecs/video/Mpeg2/Decoder.luau | 67 ++++-- tests/codecs/mpeg2.luau | 4 +- tools/bench.luau | 17 ++ tools/fixtures/mpeg2.py | 252 +++++++++++++++++++- 4 files changed, 322 insertions(+), 18 deletions(-) diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau index 4cd982c..e25801d 100644 --- a/src/Formats/codecs/video/Mpeg2/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -31,6 +31,7 @@ local readi32 = buffer.readi32 local writei32 = buffer.writei32 local band = bit32.band local bor = bit32.bor +local bxor = bit32.bxor local lshift = bit32.lshift local rshift = bit32.rshift local bswap = bit32.byteswap @@ -549,12 +550,18 @@ function D.new(maxPixels: number?): Core mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) end -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 - local mx = if mvx < 0 then -((-mvx) // 2) else mvx // 2 + local mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end local cx, cy, chh, cph, chx, chy chx = band(mx, 1) cx = mbCol * 8 + (mx - chx) // 2 if chroma == 1 then - local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end chy = band(my, 1) cy = rowY // 2 + (my - chy) // 2 chh, cph = h // 2, ph // 2 @@ -563,7 +570,11 @@ function D.new(maxPixels: number?): Core cy = rowY + (mvy - chy) // 2 chh, cph = h, ph end - local cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * cs + mbCol * 8 + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) @@ -592,8 +603,15 @@ function D.new(maxPixels: number?): Core local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then - local r = (if d == 0 then fwS else bwS) or cur :: Store - local ry, rcb, rcr = r.y, r.cb, r.cr + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr if motionType == 1 then mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) elseif motionType == 2 then @@ -736,7 +754,10 @@ function D.new(maxPixels: number?): Core dc = dcY else size = vlc(DC_CHROMA, DC_CHROMA_BITS) - dc = if b % 2 == 0 then dcCb else dcCr + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end end if size > 0 then local diff = read(size) @@ -761,14 +782,24 @@ function D.new(maxPixels: number?): Core end local v = lshift(dc, 3 - dcPrec) writei32(blk, 0, v) - parityOdd = bit32.bxor(1, band(v, 1)) - q = if luma then intraQ else chromaIntraQ + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end n = 1 else - q = if luma then nonIntraQ else chromaNonIntraQ + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST end - local lut = if mbIntra and intraVlc then DCT_B15 elseif n == 0 then DCT_FIRST else DCT_NEXT - local nextLut = if mbIntra and intraVlc then DCT_B15 else DCT_NEXT local intra = mbIntra local qs = qscale local m2 = mpeg2 @@ -853,7 +884,9 @@ function D.new(maxPixels: number?): Core if neg then m = -m end - parityOdd = bit32.bxor(parityOdd, band(m, 1)) + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end -- saturate if m > 2047 then m = 2047 @@ -887,7 +920,10 @@ function D.new(maxPixels: number?): Core off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) end else - dst = if b % 2 == 0 then curCb else curCr + dst = curCr + if b % 2 == 0 then + dst = curCb + end local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock if chroma == 1 then stride = cstride @@ -923,7 +959,10 @@ function D.new(maxPixels: number?): Core -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) local function motionVectors(d: number) - local fh, fv = if d == 0 then fc00 else fc10, if d == 0 then fc01 else fc11 + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end local o, p, f = d * 8, d * 4, d * 2 if motionType == 1 and not fieldPic then local x = decodeMotion(fh, PMV[p + 1]) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index fb3da3f..cd88a82 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -1,7 +1,7 @@ -- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and -- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan, -- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd --- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display +-- size, B-frames, dual prime, field pictures, concealment vectors) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display -- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive, -- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted -- streams never throw; the fuzz no-throw pass. @@ -24,6 +24,8 @@ local STREAMS = { require("@tests/gen/mpeg2_c422"), require("@tests/gen/mpeg2_c422_ilace"), require("@tests/gen/mpeg2_dualprime"), + require("@tests/gen/mpeg2_fields"), + require("@tests/gen/mpeg2_fields_conceal"), } local t = T.suite("codecs/mpeg2") diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..4712a7c 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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 diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py index b9e1f00..17a931b 100644 --- a/tools/fixtures/mpeg2.py +++ b/tools/fixtures/mpeg2.py @@ -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_.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]