# Motion-JPEG fixtures for codecs/image/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources, # yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame: # yuv CRC-32 of the yuv420p planes codecs/image/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes # (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged # ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact # rgba CRC-32 of djpeg -dct int (bit-exact) # ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's # IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240) # Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as # Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields, # each its own half-height JPEG with an AVI1 segment of polarity 1, back to back). # tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } }, # ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } } # tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our # encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file # tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources # Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/compress/Deflate): # Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib FF = ["-hide_banner", "-loglevel", "error", "-y"] def b64(b): return base64.b64encode(b).decode() def z64(b): return base64.b64encode(zlib.compress(b, 9)).decode() def tool(ctx, pkg, name): p = shutil.which(name) if p: return p return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip() def store(attr): return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True, capture_output=True, text=True).stdout.strip().split("\n")[0] class TurboJpeg: """the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out""" def __init__(self): lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so")) lib.tj3Init.restype = ctypes.c_void_p lib.tj3Init.argtypes = [ctypes.c_int] lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int] lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int] lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)] lib.tj3Free.argtypes = [ctypes.c_void_p] self.lib = lib self.dec = lib.tj3Init(1) self.enc = lib.tj3Init(0) def planes(self, jpeg): """-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)""" L = self.lib assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0 w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4) mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss] pw, ph = -(-w // mw) * mw, -(-h // mh) * mh cw, ch = pw // mw, ph // mh out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch) assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0 raw = out.raw return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch) def yuv420(self, jpeg): """what codecs/image/Jpeg { yuv = true } must produce for this frame""" w, h, ss, (Y, pw), cb, cr = self.planes(jpeg) out = bytearray() for y in range(h): out += Y[y * pw:y * pw + w] ow, oh = (w + 1) // 2, (h + 1) // 2 for P, cw, ch in (cb, cr): for y in range(oh): if ss == 2: out += P[y * cw:y * cw + ow] elif ss == 1: a = P[2 * y * cw:2 * y * cw + ow] b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a out += bytes((p + q + 1) >> 1 for p, q in zip(a, b)) else: r0 = P[2 * y * cw:2 * y * cw + cw] r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0 row = bytearray() for x in range(ow): x1 = min(2 * x + 1, w - 1) row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2) out += row return bytes(out) def compress420(self, yuv, w, h, quality): """yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes""" pw, ph = w + (w & 1), h + (h & 1) Y = yuv[:w * h] buf = bytearray() for y in range(ph): r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w] buf += r + r[-1:] * (pw - w) buf += yuv[w * h:] L = self.lib L.tj3Set(self.enc, 3, quality) L.tj3Set(self.enc, 4, 2) p, n = ctypes.c_void_p(), ctypes.c_size_t(0) assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0 data = ctypes.string_at(p, n.value) L.tj3Free(p) return data def split(stream): """a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)""" frames, pos = [], 0 while True: s = stream.find(b"\xff\xd8", pos) if s < 0: return frames p = s + 2 while True: m = stream[p + 1] if m == 0xD9: p += 2 break ln = (stream[p + 2] << 8) | stream[p + 3] p += 2 + ln if m == 0xDA: while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7): p += 1 frames.append(stream[s:p]) pos = p def strip_dht(jpeg): out, pos = bytearray(jpeg[:2]), 2 while pos < len(jpeg): m = jpeg[pos + 1] if m == 0xDA: out += jpeg[pos:] break ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3] if m != 0xC4: out += jpeg[pos:pos + 2 + ln] pos += 2 + ln return bytes(out) def avi1(jpeg, polarity): """an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)""" n = len(jpeg) + 18 body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big") return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:] def generate(ctx): work = tempfile.mkdtemp(prefix="formats-mjpeg-") try: _generate(ctx, work) finally: shutil.rmtree(work, ignore_errors=True) def _generate(ctx, work): ffmpeg = tool(ctx, "ffmpeg", "ffmpeg") djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg") tj = TurboJpeg() W = lambda n: os.path.join(work, n) def ff(*args): subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True) def source(src, w, h, frames, extra=()): # a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes) sw, sh = w + (w & 1), h + (h & 1) return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames), "-vf", "scale=%d:%d" % (w, h)] + list(extra) def rgba_crc(jpeg): p = W("f.jpg") open(p, "wb").write(jpeg) r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout return zlib.crc32(rgba_of_pnm(r)) def rgba_of_pnm(d): # djpeg's "P6\n \n255\n" + RGB -> RGBA parts = d.split(maxsplit=3) w, h = int(parts[1]), int(parts[2]) rgb = d[len(d) - w * h * 3:] out = bytearray(w * h * 4) out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3] out[3::4] = b"\xff" * (w * h) return bytes(out) def ffdecode(jpeg, fmt): p = W("ff.jpg") open(p, "wb").write(jpeg) o = W("ff.raw") ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o) return open(o, "rb").read() streams = [] def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None): out = W(name + ".mjpeg") ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out) frames = split(open(out, "rb").read()) assert len(frames) == nframes, (name, len(frames)) entries = [] for fr in frames: ref = fr data = mutate(fr) if mutate else fr entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)}) ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))} if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240 ref["rgba"] = z64(ffdecode(frames[0], "rgba")) streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref}) stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3")) stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3")) stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4")) stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6")) stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2")) stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2")) stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31")) # Motion-JPEG as AVI stores it: the annex K tables left out stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) # an AVI1 segment (progressive, polarity 0) and padding / junk after EOI stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"), lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8") # an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back full = W("full.yuv") ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full) fy = open(full, "rb").read() fw, fh = 320, 240 fields, fsrc = [], [] for k in range(2): rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2)) cw = fw // 2 chroma = b"" for pl in range(2): base = fw * fh + pl * cw * (fh // 2) chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2)) p = W("field%d.yuv" % k) open(p, "wb").write(rows + chroma) o = W("field%d.jpg" % k) ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p", "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) fields.append(open(o, "rb").read()) data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1) def weave(a, b, w, hf, bpp): out = bytearray() for y in range(2 * hf): src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2) out += src[k * w * bpp:(k + 1) * w * bpp] return bytes(out) ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1]) hf, cw, chf = fh // 2, fw // 2, fh // 4 wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1) for pl in range(2): o = fw * hf + pl * cw * chf wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1) def rgba_raw(jpeg): p = W("f.jpg") open(p, "wb").write(jpeg) return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout) wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4) ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh, "yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}}) # the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8 enc = [] for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)), ("mandel_176x144", "mandelbrot", 176, 144, (30, 95)), ("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)), ("one_1x1", "testsrc2", 1, 1, (90,))): p = W(name + ".yuv") ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv")) raw = open(W("s.yuv"), "rb").read() if (w, h) == (1, 1): raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source open(p, "wb").write(raw) for q in qs: want = tj.compress420(raw, w, h, q) got = ffdecode(want, "yuvj420p") if w > 1 else None psnr = 99.0 if got: se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h])) psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se) enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw), "want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)}) ctx.emit("mjpeg_enc", enc) bench = [] for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"), ("640x480 4:2:2", 640, 480, "yuvj422p")): o = W("bench.mjpeg") ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) fr = split(open(o, "rb").read())[0] bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))}) srcs = [] for w, h in ((320, 240), (640, 480)): ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv")) srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())}) ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})