# 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. # 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 # 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) # 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