Files
rosetta/tools/fixtures/mpeg2.py
T

425 lines
21 KiB
Python

# 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), 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
# each 16-line luma band), first / last = the yuv frame (base64 zlib) }
# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS,
# Matroska and AVI, base64, with the stream's crcs
# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau
import base64, os, shutil, subprocess, tempfile, zlib
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
FF = ["-hide_banner", "-loglevel", "error", "-y"]
ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"]
ILACE = ["-flags", "+ilme+ildct"]
CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64))
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
def src(kind, w, h, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
# name: (ffmpeg input + encoder args, chroma)
CASES = {
"prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1",
"-b:v", "1500k", "-bf", "1", "-g", "9"], 1),
"tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k",
"-bf", "2", "-g", "8"], 1),
"dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER,
"-b:v", "800k", "-bf", "1", "-g", "6"], 1),
"dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1),
"motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1),
"odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1),
"c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6",
"-chroma_intra_matrix", CHROMA_INTRA], 2),
"c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE +
["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2),
}
def access_units(es):
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
starts = []
i = 0
pending = None
while True:
i = es.find(b"\x00\x00\x01", i)
if i < 0 or i + 3 >= len(es):
break
code = es[i + 3]
if code in (0xB3, 0xB8) and pending is None:
pending = i
elif code == 0x00:
starts.append(pending if pending is not None else i)
pending = None
i += 3
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
def ff(args):
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
def size(path):
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path, chroma):
out = path + ".yuv"
ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo",
"-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out])
return open(out, "rb").read()
def emit(name, es, path, chroma):
w, h = size(path)
yuv = reference(path, chroma)
cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2)
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs, bands = [], []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)])
ctx.emit("mpeg2_" + name, {
"name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es),
"units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]),
})
return crcs
with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp:
crcs = {}
for name, (args, chroma) in CASES.items():
path = os.path.join(tmp, name + ".m2v")
ff(args + ENC + [path])
crcs[name] = emit(name, open(path, "rb").read(), path, chroma)
# mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires)
y4m = os.path.join(tmp, "src.y4m")
ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m])
dp = os.path.join(tmp, "dualprime.m2v")
ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'"
% (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"]}
for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")):
out = os.path.join(tmp, "prog." + ext)
ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out])
cont[ext] = b64(open(out, "rb").read())
# stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone
ts = bytearray(base64.b64decode(cont["ts"]))
patched = False
for p in range(0, len(ts), 188):
pkt = ts[p:p + 188]
if pkt[0] != 0x47 or not (pkt[1] & 0x40):
continue
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
if pid == 0 or pid == 0x11 or pkt[3] & 0x20:
continue
o = p + 5 + pkt[4]
if ts[o] != 0x02: # table_id of a PMT
continue
slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2]
pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11]
e = o + 12 + pinfo
while e < o + 3 + slen - 4:
if ts[e] == 0x02:
ts[e] = 0x80
patched = True
e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4])
crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4]))
ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big")
assert patched, "mpeg2: no PMT entry patched"
cont["ts80"] = b64(bytes(ts))
ctx.emit("mpeg2_containers", cont)
bench = []
path = os.path.join(tmp, "bench.m2v")
ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path])
es = open(path, "rb").read()
bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg2_bench", bench)
def zlib_crc32_mpeg(data):
# CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor
crc = 0xFFFFFFFF
for b in data:
crc ^= b << 24
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]