- codecs/Dct: jpeg-luau's islow / reduced IDCTs + a forward islow DCT with jcdctmgr.c's quantiser; tests/codecs/dct.luau - image/jpeg: Decode (marker parser, absorbed + reader ranges, SOF9/SOF10 + DAC, EXIF / ICC / COM / JFIF density), Scan + Color (absorbed), Arith (jdarith.c port), Encode (baseline / optimised / progressive, 444/422/420, restarts, APP1/APP2/COM from meta), Tables (annex K) - tests: 115 cjpeg/jpegtran/Pillow files, 444 decodes bit-exact with djpeg at 1, 1/2, 1/4, 1/8 (104 arithmetic), 38 encodes byte-identical to cjpeg (so djpeg decodes them), orientation, meta, truncation, fuzz - licenses: libjpeg-turbo LICENSE + README.ijg, NOTICE rows - tools/bench.luau: jpeg block; tools/bench.sh runs every fixture generator (bench blocks read their outputs)
294 lines
16 KiB
Python
294 lines
16 KiB
Python
# JPEG fixtures (tools/fixtures.py), against libjpeg-turbo's cjpeg / djpeg / jpegtran (nix libjpeg_turbo) and Pillow.
|
|
# Ported from jpeg-luau tools/fixtures.py; the TMDB test photos are replaced by ImageMagick's built-in images.
|
|
# tests/gen/jpeg_dec.luau { { name, data, err?, refs = { { scale, width, height, crc } } | cmyk = rgb bytes } }:
|
|
# cjpeg encodes of synthetic and photo-like sources at every quality / sampling /
|
|
# progression / restart / colour setting, arithmetic-coded (sequential, progressive,
|
|
# restarts, grey, 12-bit), jpegtran transcodes, stripped DHT, odd sizes, 12-bit, CMYK /
|
|
# YCCK (Pillow); references = djpeg -dct int decodes at 1, 1/2, 1/4, 1/8 (CRC-32 of the
|
|
# RGBA8 pixels), files that must be refused (lossless).
|
|
# tests/gen/jpeg_enc.luau { { name, width, height, format, pixels, opts, want } }: raw sources and what cjpeg writes
|
|
# for the same settings (our encoder must produce the same bytes).
|
|
# tests/gen/jpeg_bench.luau 1024 x 768 baseline / progressive / arithmetic files for tools/bench.luau.
|
|
import os, shutil, subprocess, tempfile, zlib
|
|
|
|
SOURCES = r'''
|
|
import os, random, sys
|
|
from PIL import Image, ImageDraw
|
|
out = sys.argv[1]
|
|
def synth(w, h, seed):
|
|
rnd = random.Random(seed)
|
|
im = Image.new("RGB", (w, h))
|
|
px = im.load()
|
|
for y in range(h):
|
|
for x in range(w):
|
|
px[x, y] = ((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), ((x + y) * 7) % 256)
|
|
d = ImageDraw.Draw(im)
|
|
for _ in range(6):
|
|
x0, y0 = rnd.randrange(w), rnd.randrange(h)
|
|
x1, y1 = x0 + rnd.randrange(1, w // 2 + 2), y0 + rnd.randrange(1, h // 2 + 2)
|
|
col = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
|
|
if rnd.random() < 0.5:
|
|
d.ellipse([x0, y0, x1, y1], fill=col)
|
|
else:
|
|
d.line([x0, y0, x1, y1], fill=col, width=rnd.randrange(1, 4))
|
|
for _ in range(w * h // 20):
|
|
x, y = rnd.randrange(w), rnd.randrange(h)
|
|
px[x, y] = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
|
|
return im
|
|
synth(97, 71, 1).save(os.path.join(out, "synth.ppm"))
|
|
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
|
|
synth(w, h, w * 100 + h).save(os.path.join(out, "s%dx%d.ppm" % (w, h)))
|
|
photo = Image.open(os.path.join(out, "photo.ppm")).convert("RGB")
|
|
photo.convert("L").save(os.path.join(out, "photo.pgm"))
|
|
with open(os.path.join(out, "photo16.ppm"), "wb") as f:
|
|
f.write(b"P6\n160 120\n65535\n")
|
|
f.write(bytes(b for v in photo.tobytes() for b in ((v * 257) >> 8, (v * 257) & 255)))
|
|
cmyk = photo.convert("CMYK")
|
|
for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})):
|
|
p = os.path.join(out, "photo_" + name + ".jpg")
|
|
cmyk.save(p, "JPEG", quality=90, **kw)
|
|
data = bytearray(open(p, "rb").read())
|
|
i = data.find(b"Adobe")
|
|
assert i > 0
|
|
data[i + 11] = 2
|
|
open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data)
|
|
for n in (name, name.replace("cmyk", "ycck")):
|
|
im = Image.open(os.path.join(out, "photo_" + n + ".jpg"))
|
|
raw = im.tobytes()
|
|
rgb = bytearray()
|
|
for k in range(0, len(raw), 4):
|
|
c, m, y, kk = raw[k:k + 4]
|
|
kk = 255 - kk
|
|
rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255))
|
|
open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb)
|
|
'''
|
|
|
|
SCANS = {
|
|
"spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
|
|
"deepsa": (
|
|
"0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n"
|
|
"0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n"
|
|
"0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n"
|
|
),
|
|
"seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n",
|
|
"dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
|
|
}
|
|
SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"}
|
|
|
|
|
|
def parse_pnm(data):
|
|
"""P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)"""
|
|
fields, pos = [], 0
|
|
while len(fields) < 4:
|
|
while data[pos:pos + 1].isspace():
|
|
pos += 1
|
|
if data[pos:pos + 1] == b"#":
|
|
while data[pos:pos + 1] != b"\n":
|
|
pos += 1
|
|
continue
|
|
s = pos
|
|
while not data[pos:pos + 1].isspace():
|
|
pos += 1
|
|
fields.append(data[s:pos])
|
|
pos += 1
|
|
magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3])
|
|
ch = 3 if magic == b"P6" else 1
|
|
n = w * h * ch
|
|
if mx < 256:
|
|
px = data[pos:pos + n]
|
|
else:
|
|
raw = data[pos:pos + 2 * n]
|
|
px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n))
|
|
if ch == 1:
|
|
px = bytes(v for v in px for _ in range(3))
|
|
return w, h, px
|
|
|
|
|
|
def rgba_crc(rgb):
|
|
out = bytearray(len(rgb) // 3 * 4)
|
|
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
|
|
out[3::4] = b"\xff" * (len(rgb) // 3)
|
|
return zlib.crc32(bytes(out))
|
|
|
|
|
|
def generate(ctx):
|
|
bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip())
|
|
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
|
|
work = tempfile.mkdtemp(prefix="formats-jpeg-")
|
|
try:
|
|
_generate(ctx, bindir, magick, work)
|
|
finally:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
|
|
|
|
def _generate(ctx, bindir, magick, work):
|
|
def run(tool, *args):
|
|
exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool)
|
|
r = subprocess.run([exe] + list(args), capture_output=True)
|
|
if r.returncode != 0:
|
|
raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode()))
|
|
return r.stdout
|
|
|
|
W = lambda n: os.path.join(work, n)
|
|
# photo-like sources: ImageMagick's built-in rose, and a plasma fractal
|
|
run(magick, "rose:", "-resize", "160x120!", W("photo.ppm"))
|
|
run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm"))
|
|
ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work)))
|
|
for k, v in SCANS.items():
|
|
with open(W(k + ".scans"), "w") as f:
|
|
f.write(v)
|
|
SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")}
|
|
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
|
|
SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h))
|
|
|
|
cases = [] # (name, path, scales | "cmyk", err)
|
|
|
|
def cj(name, src, *args, scales=(1, 2, 4, 8), err=None):
|
|
out = W(name + ".jpg")
|
|
run("cjpeg", *args, "-outfile", out, SRC[src])
|
|
cases.append((name, out, scales, err))
|
|
|
|
for q in (30, 90):
|
|
for sn, s in SAMPLINGS.items():
|
|
cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s)
|
|
cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive")
|
|
for sn, s in SAMPLINGS.items():
|
|
cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s)
|
|
cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive")
|
|
cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2")
|
|
cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive")
|
|
cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2")
|
|
cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive")
|
|
cj("photo_optimize", "photo", "-quality", "80", "-optimize")
|
|
cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1")
|
|
cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1")
|
|
cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1")
|
|
cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2")
|
|
cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive")
|
|
cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans"))
|
|
cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1")
|
|
cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B")
|
|
cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive")
|
|
cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive")
|
|
cj("photo_gray", "photo", "-grayscale")
|
|
cj("photo_gray_prog", "photo", "-grayscale", "-progressive")
|
|
cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B")
|
|
cj("photo_rgb", "photo", "-rgb")
|
|
cj("photo_rgb_prog", "photo", "-rgb", "-progressive")
|
|
for k in SCANS:
|
|
cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans"))
|
|
cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans"))
|
|
cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2")
|
|
cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive")
|
|
cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale")
|
|
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
|
|
cj("tiny_%s_420" % k, k, "-sample", "2x2")
|
|
cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive")
|
|
cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95")
|
|
cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic")
|
|
# arithmetic coding
|
|
for sn in ("444", "420", "422"):
|
|
cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn])
|
|
cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn])
|
|
cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5")
|
|
cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100")
|
|
cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1")
|
|
cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B")
|
|
cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale")
|
|
cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive")
|
|
cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb")
|
|
cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2")
|
|
cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive")
|
|
cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans"))
|
|
cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans"))
|
|
cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans"))
|
|
# refused
|
|
cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless")
|
|
|
|
base = W("photo_q90_420.jpg")
|
|
for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]),
|
|
("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])):
|
|
out = W("photo_" + name + ".jpg")
|
|
run("jpegtran", *args, "-outfile", out, base)
|
|
cases.append(("photo_" + name, out, (1, 2, 4, 8), None))
|
|
# an arithmetic file back to Huffman
|
|
out = W("photo_tran_unarith.jpg")
|
|
run("jpegtran", "-outfile", out, W("photo_arith_420.jpg"))
|
|
cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None))
|
|
|
|
# stripped DHT: the standard tables
|
|
data = open(base, "rb").read()
|
|
out, pos = bytearray(data[:2]), 2
|
|
while pos < len(data):
|
|
m = data[pos + 1]
|
|
if m == 0xDA:
|
|
out += data[pos:]
|
|
break
|
|
ln = (data[pos + 2] << 8) | data[pos + 3]
|
|
if m != 0xC4:
|
|
out += data[pos:pos + 2 + ln]
|
|
pos += 2 + ln
|
|
open(W("photo_nodht.jpg"), "wb").write(bytes(out))
|
|
cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None))
|
|
for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"):
|
|
cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None))
|
|
|
|
dec = []
|
|
for name, path, scales, err in cases:
|
|
e = {"name": name, "data": open(path, "rb").read()}
|
|
if err:
|
|
e["err"] = err
|
|
if scales == "cmyk":
|
|
e["cmyk"] = open(path[:-4] + ".ref", "rb").read()
|
|
else:
|
|
refs = []
|
|
for s in scales:
|
|
args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path]
|
|
w, h, px = parse_pnm(run("djpeg", *args))
|
|
refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)})
|
|
e["refs"] = refs
|
|
dec.append(e)
|
|
ctx.emit("jpeg_dec", dec)
|
|
|
|
# encoder: cjpeg's bytes for the same settings
|
|
enc = []
|
|
|
|
def ce(name, src, fmt, opts, *args):
|
|
out = W("enc_" + name + ".jpg")
|
|
run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src])
|
|
w, h, px = parse_pnm(open(SRC[src], "rb").read())
|
|
if fmt == "gray8":
|
|
px = px[0::3]
|
|
enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts,
|
|
"want": open(out, "rb").read()})
|
|
|
|
for q in (10, 50, 75, 90, 100):
|
|
ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2")
|
|
for sn in ("444", "422", "420"):
|
|
ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
|
|
ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
|
|
ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
|
|
ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
|
|
ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize")
|
|
ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80")
|
|
ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive")
|
|
ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale")
|
|
ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B")
|
|
ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive")
|
|
ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive")
|
|
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
|
|
ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2")
|
|
ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive")
|
|
ctx.emit("jpeg_enc", enc)
|
|
|
|
SRC["big"] = W("big.ppm")
|
|
bench = []
|
|
for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]),
|
|
("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])):
|
|
out = W("bench.jpg")
|
|
run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"])
|
|
w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out))
|
|
bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)})
|
|
w, h, px = parse_pnm(open(SRC["big"], "rb").read())
|
|
ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px})
|