345 lines
18 KiB
Python
345 lines
18 KiB
Python
# WebP fixtures (tools/fixtures.py). Reference tools: libwebp 1.6 (cwebp, dwebp, img2webp, gif2webp, webpmux),
|
|
# ImageMagick (built-in test images, an animated GIF), ffmpeg's libvpx (VP8 key frames from a second encoder, with
|
|
# token partitions and loop filter deltas, wrapped in a RIFF here) and Pillow (WebPAnimDecoder: composited frames).
|
|
# tests/gen/webp_src.luau the source images: { name, width, height, rgba }
|
|
# tests/gen/webp_cases.luau still files: { name, data, width, height, crc (dwebp -pam), lossy, yuv (dwebp -yuv),
|
|
# nofancy (dwebp -nofancy -pam), alpha, meta }
|
|
# tests/gen/webp_anim.luau animations: { name, data, width, height, loops, frames = { crc, ms } (Pillow) }
|
|
# tests/gen/webp_enc.luau our encoder's output checked by dwebp / Pillow (tools/fixtures/_webp_encode.luau):
|
|
# { name, effort, crc, ok, size, cwebp }, animations { name, crc, frames }
|
|
# tests/gen/webp_bench.luau bigger lossy / lossless files for tools/bench.luau
|
|
import json, os, random, shutil, struct, subprocess, tempfile, zlib
|
|
|
|
INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Rosetta/codecs/image/Vp8L", "src/Rosetta/image/webp"]
|
|
|
|
TOOLS = ["libwebp", "imagemagick", "ffmpeg"]
|
|
|
|
|
|
def run(tmp, script):
|
|
path = os.path.join(tmp, "run.sh")
|
|
with open(path, "w") as f:
|
|
f.write("set -e\n" + script)
|
|
cmd = ["nix", "shell"] + ["nixpkgs#" + t for t in TOOLS] + ["-c", "bash", path]
|
|
subprocess.run(cmd, cwd=tmp, check=True, capture_output=True)
|
|
|
|
|
|
def pam_write(path, w, h, rgba):
|
|
with open(path, "wb") as f:
|
|
f.write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(rgba))
|
|
|
|
|
|
def pam_read(data):
|
|
end = data.index(b"ENDHDR\n") + 7
|
|
hdr = dict(l.split(b" ", 1) for l in data[:end].split(b"\n")[1:] if b" " in l)
|
|
w, h, d = int(hdr[b"WIDTH"]), int(hdr[b"HEIGHT"]), int(hdr[b"DEPTH"])
|
|
px = data[end:end + w * h * d]
|
|
if d == 4:
|
|
return w, h, px
|
|
out = bytearray(w * h * 4)
|
|
for i in range(w * h):
|
|
if d == 3:
|
|
out[i * 4:i * 4 + 3] = px[i * 3:i * 3 + 3]
|
|
else:
|
|
out[i * 4:i * 4 + 3] = bytes([px[i * d]]) * 3
|
|
out[i * 4 + 3] = 255 if d < 2 or d == 3 else px[i * d + 1]
|
|
return w, h, bytes(out)
|
|
|
|
|
|
def synthetic(rng):
|
|
out = []
|
|
|
|
def img(name, w, h, f):
|
|
px = bytearray()
|
|
for y in range(h):
|
|
for x in range(w):
|
|
px += bytes(f(x, y))
|
|
out.append((name, w, h, bytes(px)))
|
|
|
|
img("tiny", 1, 1, lambda x, y: (200, 10, 30, 255))
|
|
img("odd", 3, 7, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 255))
|
|
img("strip", 257, 3, lambda x, y: ((x * 7) & 255, (x + y * 50) & 255, (x * x) & 255, 255))
|
|
two = [(0, 0, 0, 255), (255, 255, 255, 255)]
|
|
img("pal2", 33, 17, lambda x, y: two[(x * 3 + y * 5) % 7 < 3])
|
|
three = [(255, 0, 0, 255), (0, 255, 0, 128), (0, 0, 255, 0)]
|
|
img("pal3", 40, 9, lambda x, y: three[(x // 3 + y) % 3])
|
|
five = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for _ in range(5)]
|
|
img("pal5", 25, 25, lambda x, y: five[(x * y + x) % 5])
|
|
p16 = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.choice([255, 255, 90])) for _ in range(16)]
|
|
img("pal16", 64, 40, lambda x, y: p16[((x // 4) * 3 + y // 5) % 16])
|
|
p17 = [(i * 15, 255 - i * 15, (i * 77) & 255, 255) for i in range(17)]
|
|
img("pal17", 51, 30, lambda x, y: p17[(x + y) % 17])
|
|
p256 = [(i, (i * 3) & 255, (i * 7) & 255, 255 if i % 9 else 128) for i in range(256)]
|
|
img("pal256", 64, 64, lambda x, y: p256[(x * 64 + y * 5 + x * y) % 256])
|
|
img("noise", 48, 48, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)))
|
|
img("grad", 100, 60, lambda x, y: (x * 255 // 99, y * 255 // 59, (x + y) * 255 // 158, min(255, x * 3 + y)))
|
|
img("trans", 50, 50, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 0 if (x - 25) ** 2 + (y - 25) ** 2 > 300 else 255))
|
|
return out
|
|
|
|
|
|
def add_alpha(name, w, h, px, kind):
|
|
out = bytearray(px)
|
|
for y in range(h):
|
|
for x in range(w):
|
|
i = (y * w + x) * 4 + 3
|
|
if kind == "ramp":
|
|
out[i] = 0 if x < w // 6 else min(255, (x * 255) // max(1, w - 1) + 20)
|
|
else:
|
|
out[i] = 255 if (x // 8 + y // 8) % 3 else (x * y) & 255
|
|
return name, w, h, bytes(out)
|
|
|
|
|
|
LOSSLESS = [("z0", "-lossless -z 0"), ("z3", "-lossless -z 3"), ("z6", "-lossless -z 6"), ("z9", "-lossless -z 9"),
|
|
("exact", "-lossless -exact -m 6 -q 100"), ("near", "-lossless -near_lossless 40")]
|
|
LOSSY = [("q5", "-q 5"), ("q50", "-q 50"), ("q90", "-q 90 -m 6"), ("simple", "-q 75 -nostrong -sharpness 5"),
|
|
("seg1", "-q 30 -f 100 -segments 1"), ("nofilter", "-q 60 -sns 0 -f 0"), ("sharpyuv", "-q 80 -sharp_yuv -af")]
|
|
ALPHA = [("araw", "-q 70 -alpha_method 0"), ("afnone", "-q 70 -alpha_filter none"), ("affast", "-q 70 -alpha_filter fast"),
|
|
("afbest", "-q 70 -alpha_filter best -exact"), ("aq30", "-q 70 -alpha_q 30")]
|
|
FULL = {"rose", "plasma", "rose_a", "pal16", "grad", "odd"} # every lossless / lossy variant; others get a few
|
|
|
|
|
|
def ivf_frames(data):
|
|
frames, p = [], 32
|
|
while p + 12 <= len(data):
|
|
n = struct.unpack_from("<I", data, p)[0]
|
|
frames.append(data[p + 12:p + 12 + n])
|
|
p += 12 + n
|
|
return frames
|
|
|
|
|
|
def riff(chunks):
|
|
body = b"WEBP"
|
|
for fourcc, payload in chunks:
|
|
body += fourcc + struct.pack("<I", len(payload)) + payload + (b"\0" if len(payload) % 2 else b"")
|
|
return b"RIFF" + struct.pack("<I", len(body)) + body
|
|
|
|
|
|
def chunks_of(data):
|
|
out, p = [], 12
|
|
while p + 8 <= len(data):
|
|
fourcc, n = data[p:p + 4], struct.unpack_from("<I", data, p + 4)[0]
|
|
out.append((fourcc, data[p + 8:p + 8 + n]))
|
|
p += 8 + n + n % 2
|
|
return out
|
|
|
|
|
|
def filter_alpha(a, w, h, f):
|
|
out = bytearray(w * h)
|
|
for y in range(h):
|
|
for x in range(w):
|
|
i = y * w + x
|
|
if f == 0:
|
|
pred = 0
|
|
elif y == 0:
|
|
pred = a[i - 1] if x else 0
|
|
elif x == 0:
|
|
pred = a[i - w]
|
|
elif f == 1:
|
|
pred = a[i - 1]
|
|
elif f == 2:
|
|
pred = a[i - w]
|
|
else:
|
|
pred = max(0, min(255, a[i - 1] + a[i - w] - a[i - w - 1]))
|
|
out[i] = (a[i] - pred) & 255
|
|
return bytes(out)
|
|
|
|
|
|
def craft_alpha(tmp, base_alpha):
|
|
name, w, h, px = base_alpha
|
|
a = bytes(px[i] for i in range(3, len(px), 4))
|
|
src = dict(chunks_of(open(os.path.join(tmp, "rose_a_afnone.webp"), "rb").read()))
|
|
out = []
|
|
for f in range(4):
|
|
alph = bytes([f << 2]) + filter_alpha(a, w, h, f)
|
|
data = riff([(b"VP8X", src[b"VP8X"]), (b"ALPH", alph), (b"VP8 ", src[b"VP8 "])])
|
|
fname = "alph_raw_f%d.webp" % f
|
|
open(os.path.join(tmp, fname), "wb").write(data)
|
|
out.append((fname, {"lossy": True}))
|
|
return out
|
|
|
|
|
|
def generate(ctx):
|
|
tmp = tempfile.mkdtemp(prefix="webp_fx_")
|
|
try:
|
|
_generate(ctx, tmp)
|
|
finally:
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
|
|
|
|
def _generate(ctx, tmp):
|
|
rng = ctx.rng(20260)
|
|
# 1. sources: ImageMagick's built-in images (resized) + synthetic ones
|
|
run(tmp, "\n".join([
|
|
"magick rose: -alpha off PAM:rose.pam",
|
|
"magick granite: -alpha off PAM:granite.pam",
|
|
"magick netscape: -alpha off PAM:netscape.pam",
|
|
"magick wizard: -resize 120x160 -alpha off PAM:wizard.pam",
|
|
"magick logo: -resize 160x120 -alpha off PAM:logo.pam",
|
|
"magick -seed 7 -size 200x150 plasma:fractal -depth 8 -alpha off PAM:plasma.pam",
|
|
"magick wizard: -resize 512x512! -alpha off PAM:bench.pam",
|
|
]))
|
|
sources = []
|
|
for n in ["rose", "granite", "netscape", "wizard", "logo", "plasma"]:
|
|
w, h, px = pam_read(open(os.path.join(tmp, n + ".pam"), "rb").read())
|
|
sources.append((n, w, h, px))
|
|
base = {s[0]: s for s in sources}
|
|
sources.append(add_alpha("rose_a", *base["rose"][1:], "ramp"))
|
|
sources.append(add_alpha("plasma_a", *base["plasma"][1:], "blocks"))
|
|
sources += synthetic(rng)
|
|
for n, w, h, px in sources:
|
|
pam_write(os.path.join(tmp, n + ".pam"), w, h, px)
|
|
ctx.emit("webp_src", [{"name": n, "width": w, "height": h, "rgba": px} for n, w, h, px in sources])
|
|
|
|
# 2. still files: cwebp lossless / lossy / alpha variants, libvpx key frames, metadata
|
|
files = [] # (name, extra info)
|
|
lines = []
|
|
for n, w, h, px in sources:
|
|
has_alpha = any(px[i] != 255 for i in range(3, len(px), 4))
|
|
full = n in FULL
|
|
for tag, args in LOSSLESS if full else LOSSLESS[2:3]:
|
|
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
|
files.append(("%s_%s.webp" % (n, tag), {"lossy": False}))
|
|
for tag, args in LOSSY if full else LOSSY[1:2]:
|
|
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
|
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
|
|
if has_alpha:
|
|
for tag, args in ALPHA if full or n == "plasma_a" else ALPHA[1:2]:
|
|
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
|
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
|
|
for n in ["rose", "granite", "plasma", "wizard"]:
|
|
for k, (slices, q) in enumerate([(1, 10), (2, 30), (4, 50), (8, 63)]):
|
|
lines.append("magick %s.pam -alpha off PNG24:%s_vpx.png" % (n, n))
|
|
lines.append("ffmpeg -loglevel error -y -i %s_vpx.png -c:v libvpx -slices %d -qmin %d -qmax %d -b:v 1M -sharpness %d -f ivf %s_vpx%d.ivf"
|
|
% (n, slices, q, q, k, n, k))
|
|
lines.append("cwebp -quiet -q 60 rose_a.pam -o meta_base.webp")
|
|
lines.append("head -c 600 /dev/urandom > meta.icc && head -c 100 /dev/urandom > meta.exif && printf '<x:xmpmeta/>' > meta.xmp")
|
|
lines.append("webpmux -set icc meta.icc meta_base.webp -o meta1.webp")
|
|
lines.append("webpmux -set exif meta.exif meta1.webp -o meta2.webp")
|
|
lines.append("webpmux -set xmp meta.xmp meta2.webp -o meta_all.webp")
|
|
lines.append("cwebp -quiet -lossless -metadata all rose.pam -o meta_ll.webp && webpmux -set icc meta.icc meta_ll.webp -o meta_ll_icc.webp")
|
|
files.append(("meta_all.webp", {"lossy": True, "meta": True}))
|
|
files.append(("meta_ll_icc.webp", {"lossy": False, "meta": True}))
|
|
run(tmp, "\n".join(lines))
|
|
for n in ["rose", "granite", "plasma", "wizard"]:
|
|
for k in range(4):
|
|
data = open(os.path.join(tmp, "%s_vpx%d.ivf" % (n, k)), "rb").read()
|
|
frame = ivf_frames(data)[0]
|
|
name = "%s_vpx%d.webp" % (n, k)
|
|
open(os.path.join(tmp, name), "wb").write(riff([(b"VP8 ", frame)]))
|
|
files.append((name, {"lossy": True}))
|
|
# raw ALPH chunks with each of the four filters, written here (rose_a's alpha over its lossy VP8 data)
|
|
files += craft_alpha(tmp, base_alpha=[s for s in sources if s[0] == "rose_a"][0])
|
|
# references
|
|
lines = []
|
|
for name, info in files:
|
|
lines.append("dwebp -quiet %s -pam -o %s.pam" % (name, name))
|
|
if info["lossy"]:
|
|
lines.append("dwebp -quiet %s -nofancy -pam -o %s.nf.pam" % (name, name))
|
|
lines.append("dwebp -quiet %s -yuv -o %s.yuv" % (name, name))
|
|
run(tmp, "\n".join(lines))
|
|
cases = []
|
|
for name, info in files:
|
|
data = open(os.path.join(tmp, name), "rb").read()
|
|
w, h, px = pam_read(open(os.path.join(tmp, name + ".pam"), "rb").read())
|
|
c = {"name": name, "data": data, "width": w, "height": h, "crc": zlib.crc32(px), "lossy": info["lossy"],
|
|
"alpha": any(px[i] != 255 for i in range(3, len(px), 4))}
|
|
if info["lossy"]:
|
|
c["nofancy"] = zlib.crc32(pam_read(open(os.path.join(tmp, name + ".nf.pam"), "rb").read())[2])
|
|
c["yuv"] = zlib.crc32(open(os.path.join(tmp, name + ".yuv"), "rb").read())
|
|
if info.get("meta"):
|
|
c["icc"] = zlib.crc32(open(os.path.join(tmp, "meta.icc"), "rb").read())
|
|
if name == "meta_all.webp":
|
|
c["exif"] = zlib.crc32(open(os.path.join(tmp, "meta.exif"), "rb").read())
|
|
c["xmp"] = "<x:xmpmeta/>"
|
|
cases.append(c)
|
|
ctx.emit("webp_cases", cases)
|
|
|
|
# 3. animations: img2webp (sub-rectangles, blending, mixed lossy / lossless), gif2webp, webpmux frames
|
|
lines = []
|
|
# frames of one canvas size: rose-sized crops of the sources
|
|
for i, (n, w, h, px) in enumerate([s for s in sources if s[0] in ("plasma", "plasma_a", "wizard", "grad", "noise", "netscape")]):
|
|
lines.append("magick %s.pam -resize 70x46! -depth 8 PAM:af%d.pam" % (n, i))
|
|
lines.append("magick rose.pam -fill red -draw 'rectangle 10,10 30,20' PAM:af6.pam")
|
|
lines.append("magick rose.pam -fill blue -draw 'rectangle 40,20 60,40' PAM:af7.pam")
|
|
lines.append("magick rose.pam -alpha on -channel A -evaluate set 50%% +channel PAM:af8.pam")
|
|
lines.append("img2webp -loop 3 -lossless rose.pam -d 80 af6.pam -d 120 af7.pam af8.pam -lossy -q 60 af0.pam -o anim_mixed.webp")
|
|
lines.append("img2webp -min_size -lossless af1.pam af3.pam -d 40 af4.pam af8.pam -o anim_alpha.webp")
|
|
lines.append("img2webp -kmax 2 -lossy -q 40 af0.pam af2.pam af5.pam -mixed af6.pam af7.pam -o anim_lossy.webp")
|
|
lines.append("magick -dispose background -delay 10 -size 60x40 xc:none -fill red -draw 'circle 20,20 30,20' "
|
|
"-dispose previous -delay 20 -size 60x40 xc:none -fill blue -draw 'rectangle 5,5 25,30' "
|
|
"-dispose none -delay 30 -size 60x40 xc:none -fill green -draw 'rectangle 30,10 55,35' "
|
|
"-loop 0 anim.gif")
|
|
lines.append("gif2webp -quiet anim.gif -o anim_gif.webp")
|
|
lines.append("gif2webp -quiet -lossy -q 50 anim.gif -o anim_gif_lossy.webp")
|
|
lines.append("cwebp -quiet -lossless af6.pam -o fr1.webp && cwebp -quiet -q 50 af7.pam -o fr2.webp")
|
|
lines.append("webpmux -frame fr1.webp +100+0+0+0-b -frame fr2.webp +50+10+6+1+b -loop 1 -bgcolor 255,1,2,3 -o anim_mux.webp")
|
|
lines.append("webpmux -set icc meta.icc anim_mux.webp -o anim_mux_icc.webp")
|
|
run(tmp, "\n".join(lines))
|
|
anims = ["anim_mixed.webp", "anim_alpha.webp", "anim_lossy.webp", "anim_gif.webp", "anim_gif_lossy.webp", "anim_mux_icc.webp"]
|
|
ref = pillow_frames(ctx, [os.path.join(tmp, a) for a in anims])
|
|
out = []
|
|
for a, r in zip(anims, ref):
|
|
out.append({"name": a, "data": open(os.path.join(tmp, a), "rb").read(), "width": r["w"], "height": r["h"],
|
|
"loops": r["loop"], "rgba": r["mode"] == "RGBA", "frames": [{"crc": c, "ms": d} for c, d in r["frames"]]})
|
|
ctx.emit("webp_anim", out)
|
|
|
|
# 4. our encoder, checked by dwebp (still) and Pillow (animations)
|
|
res = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_webp_encode.luau"],
|
|
cwd=ctx.root, check=True, capture_output=True).stdout.decode()
|
|
ours = []
|
|
for line in res.split("\n"):
|
|
if line.strip():
|
|
name, hexdata = line.split(" ")
|
|
path = os.path.join(tmp, "ours_" + name.split(":")[0] + ".webp")
|
|
open(path, "wb").write(bytes.fromhex(hexdata))
|
|
ours.append((name, path))
|
|
run(tmp, "\n".join("dwebp -quiet %s -pam -o %s.pam" % (p, p) for n, p in ours if not n.startswith("anim")) + "\n" +
|
|
"\n".join("cwebp -quiet -lossless -exact %s.pam -o cw_%s.webp" % (n, n) for n, w, h, px in sources))
|
|
src = {n: (w, h, px) for n, w, h, px in sources}
|
|
enc = []
|
|
anim_paths = [(n, p) for n, p in ours if n.startswith("anim")]
|
|
aref = pillow_frames(ctx, [p for n, p in anim_paths])
|
|
for name, path in ours:
|
|
if name.startswith("anim"):
|
|
continue
|
|
sname, effort, mode = name.rsplit("_", 2)
|
|
w, h, px = src[sname]
|
|
_, _, got = pam_read(open(path + ".pam", "rb").read())
|
|
want = px if mode == "exact" else bytes(b if px[(i // 4) * 4 + 3] else 0 for i, b in enumerate(px))
|
|
enc.append({"name": sname, "effort": int(effort[1:]), "exact": mode == "exact", "ok": got == want,
|
|
"size": os.path.getsize(path), "cwebp": os.path.getsize(os.path.join(tmp, "cw_%s.webp" % sname))})
|
|
anim_out = []
|
|
for (n, p), r in zip(anim_paths, aref):
|
|
aname, want = n.split(":")
|
|
got = [c for c, d in r["frames"]]
|
|
anim_out.append({"name": aname, "data": open(p, "rb").read(), "frames": got, "ms": [d for c, d in r["frames"]],
|
|
"loops": r["loop"], "ok": got == [int(c) for c in want.split(",")]})
|
|
ctx.emit("webp_enc", {"still": enc, "anim": anim_out})
|
|
|
|
# 5. bench: a 512 x 512 lossy and lossless file
|
|
run(tmp, "cwebp -quiet -q 80 bench.pam -o bench_lossy.webp\ncwebp -quiet -lossless bench.pam -o bench_ll.webp")
|
|
w, h, px = pam_read(open(os.path.join(tmp, "bench.pam"), "rb").read())
|
|
ctx.emit("webp_bench", {"width": w, "height": h, "rgba": px,
|
|
"lossy": open(os.path.join(tmp, "bench_lossy.webp"), "rb").read(),
|
|
"lossless": open(os.path.join(tmp, "bench_ll.webp"), "rb").read()})
|
|
|
|
|
|
PILLOW = r"""
|
|
import json, sys, zlib
|
|
from PIL import Image
|
|
out = []
|
|
for path in sys.argv[1:]:
|
|
im = Image.open(path)
|
|
frames = []
|
|
for i in range(getattr(im, "n_frames", 1)):
|
|
im.seek(i)
|
|
frames.append([zlib.crc32(im.convert("RGBA").tobytes()), im.info.get("duration", 0)])
|
|
out.append({"w": im.width, "h": im.height, "mode": im.mode, "loop": im.info.get("loop", 0), "frames": frames})
|
|
print(json.dumps(out))
|
|
"""
|
|
|
|
|
|
def pillow_frames(ctx, paths):
|
|
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.pillow])"
|
|
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", PILLOW] + paths
|
|
return json.loads(subprocess.run(cmd, capture_output=True, check=True).stdout)
|