221 lines
11 KiB
Python
221 lines
11 KiB
Python
# APNG fixtures (tools/fixtures.py).
|
|
# tests/gen/apng_cases.luau animated PNGs with the reference composited canvases (CRC-32 of each full rgba8 frame)
|
|
# - made by ffmpeg's apng encoder (sub-rectangles, dispose / blend chosen by ffmpeg, -plays)
|
|
# - written here by hand: every dispose op (none / background / previous) and blend op (source / over) on
|
|
# sub-rectangles with partial alpha, a hidden default image (IDAT not part of the animation), palette + tRNS,
|
|
# grey, RGB, a first frame with dispose previous, split fdATs
|
|
# The reference canvases come from ffmpeg (`-f apng -i x -f rawvideo -pix_fmt rgba`); a small compositor here
|
|
# (the same integer blend as ffmpeg's pngdec.c) must agree with ffmpeg, so a broken reference is caught too.
|
|
# Files ffmpeg cannot represent (the hidden default image) use the compositor here alone.
|
|
import os, random, struct, subprocess, tempfile, zlib
|
|
|
|
|
|
def chunk(t, d):
|
|
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
|
|
|
|
|
CH = {0: 1, 2: 3, 3: 1, 6: 4}
|
|
|
|
|
|
def raw_rows(px, w, h, ct, rng):
|
|
"""px: list of h rows of w sample tuples -> filtered (random filter per row) scanlines"""
|
|
ch = CH[ct]
|
|
out = bytearray()
|
|
prev = None
|
|
for y in range(h):
|
|
row = bytes(s for p in px[y] for s in p)
|
|
ft = rng.randrange(5)
|
|
out.append(ft)
|
|
for i, x in enumerate(row):
|
|
a = row[i - ch] if i >= ch else 0
|
|
b = prev[i] if prev else 0
|
|
c = prev[i - ch] if prev and i >= ch else 0
|
|
if ft == 4:
|
|
p = a + b - c
|
|
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
|
pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
|
|
else:
|
|
pred = (0, a, b, (a + b) // 2)[ft]
|
|
out.append((x - pred) & 255)
|
|
prev = row
|
|
return bytes(out)
|
|
|
|
|
|
def to_rgba(ct, s, plte=None, trns=None):
|
|
if ct == 6:
|
|
return tuple(s)
|
|
if ct == 2:
|
|
return (s[0], s[1], s[2], 255)
|
|
if ct == 0:
|
|
return (s[0], s[0], s[0], 255)
|
|
c = plte[s[0]]
|
|
a = trns[s[0]] if trns and s[0] < len(trns) else 255
|
|
return (c[0], c[1], c[2], a)
|
|
|
|
|
|
def apng(w, h, ct, frames, plays=0, default=None, plte=None, trns=None, rng=None, split=1):
|
|
"""frames: list of dict(x, y, w, h, px, num, den, dispose, blend); default: px of a hidden default image"""
|
|
rng = rng or random.Random(1)
|
|
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, ct, 0, 0, 0))
|
|
out += chunk(b"acTL", struct.pack(">II", len(frames), plays))
|
|
if plte:
|
|
out += chunk(b"PLTE", b"".join(bytes(c) for c in plte))
|
|
if trns:
|
|
out += chunk(b"tRNS", bytes(trns))
|
|
seq = 0
|
|
if default is not None:
|
|
out += chunk(b"IDAT", zlib.compress(raw_rows(default, w, h, ct, rng)))
|
|
for i, f in enumerate(frames):
|
|
out += chunk(b"fcTL", struct.pack(">IIIIIHHBB", seq, f["w"], f["h"], f["x"], f["y"], f["num"], f["den"], f["dispose"], f["blend"]))
|
|
seq += 1
|
|
z = zlib.compress(raw_rows(f["px"], f["w"], f["h"], ct, rng))
|
|
step = max(1, -(-len(z) // split))
|
|
for k in range(0, len(z), step):
|
|
if i == 0 and default is None:
|
|
out += chunk(b"IDAT", z[k:k + step])
|
|
else:
|
|
out += chunk(b"fdAT", struct.pack(">I", seq) + z[k:k + step])
|
|
seq += 1
|
|
return out + chunk(b"IEND", b"")
|
|
|
|
|
|
def div255(x):
|
|
return ((x + 128) * 257) >> 16
|
|
|
|
|
|
def composite(w, h, ct, frames, plte=None, trns=None):
|
|
"""full rgba8 canvases (bytes), blending like ffmpeg's pngdec.c (APNG spec semantics)"""
|
|
canvas = [(0, 0, 0, 0)] * (w * h)
|
|
outs = []
|
|
for i, f in enumerate(frames):
|
|
dispose, blend = f["dispose"], f["blend"]
|
|
if i == 0:
|
|
blend = 0
|
|
if dispose == 2:
|
|
dispose = 1
|
|
saved = list(canvas)
|
|
for yy in range(f["h"]):
|
|
for xx in range(f["w"]):
|
|
src = to_rgba(ct, f["px"][yy][xx], plte, trns)
|
|
k = (f["y"] + yy) * w + f["x"] + xx
|
|
if blend == 0 or src[3] == 255:
|
|
canvas[k] = src
|
|
elif src[3] == 0:
|
|
pass
|
|
else:
|
|
fa, bg = src[3], canvas[k]
|
|
ba = bg[3]
|
|
oa = fa + div255((255 - fa) * ba)
|
|
if ba == 255:
|
|
canvas[k] = tuple(div255(fa * src[c] + (255 - fa) * bg[c]) for c in range(3)) + (oa,)
|
|
else:
|
|
canvas[k] = tuple((255 * fa * src[c] + (255 - fa) * ba * bg[c]) // (255 * oa) for c in range(3)) + (oa,)
|
|
outs.append(b"".join(bytes(p) for p in canvas))
|
|
if dispose == 1:
|
|
for yy in range(f["h"]):
|
|
for xx in range(f["w"]):
|
|
canvas[(f["y"] + yy) * w + f["x"] + xx] = (0, 0, 0, 0)
|
|
elif dispose == 2:
|
|
canvas = saved
|
|
return outs
|
|
|
|
|
|
def ffmpeg_frames(ctx, data, w, h):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
p = os.path.join(tmp, "in.png")
|
|
with open(p, "wb") as f:
|
|
f.write(data)
|
|
raw = subprocess.run(["ffmpeg", "-v", "error", "-f", "apng", "-i", p, "-f", "rawvideo", "-pix_fmt", "rgba", "-fps_mode", "passthrough", "-"],
|
|
capture_output=True, check=True).stdout
|
|
n = w * h * 4
|
|
return [raw[i:i + n] for i in range(0, len(raw), n)]
|
|
|
|
|
|
def sprite(rng, w, h, ct, alpha=True, ncolors=None):
|
|
px = []
|
|
for y in range(h):
|
|
row = []
|
|
for x in range(w):
|
|
if ct == 3:
|
|
row.append((rng.randrange(ncolors),))
|
|
elif ct == 0:
|
|
row.append(((x * 17 + y * 5 + rng.randrange(8)) & 255,))
|
|
elif ct == 2:
|
|
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255))
|
|
else:
|
|
a = rng.choice((0, 255, 255, rng.randrange(256))) if alpha else 255
|
|
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255, a))
|
|
px.append(row)
|
|
return px
|
|
|
|
|
|
def frame(rng, ct, x, y, w, h, dispose, blend, num=1, den=10, **kw):
|
|
return {"x": x, "y": y, "w": w, "h": h, "px": sprite(rng, w, h, ct, **kw), "num": num, "den": den, "dispose": dispose, "blend": blend}
|
|
|
|
|
|
def generate(ctx):
|
|
rng = random.Random(77)
|
|
cases = []
|
|
|
|
def add(name, data, w, h, frames_meta, refs, default_crc=None, plays=0, ffmpeg=True, opaque=False):
|
|
c = {"name": name, "data": data, "width": w, "height": h, "plays": plays,
|
|
"frames": [{"x": f["x"], "y": f["y"], "w": f["w"], "h": f["h"], "num": f["num"], "den": f["den"], "dispose": f["dispose"], "blend": f["blend"]} for f in frames_meta],
|
|
"crcs": [zlib.crc32(r) for r in refs], "ffmpeg": ffmpeg, "opaque": opaque}
|
|
if default_crc is not None:
|
|
c["defaultCrc"] = default_crc
|
|
cases.append(c)
|
|
|
|
def hand(name, w, h, ct, frames, plays=0, plte=None, trns=None, split=1):
|
|
data = apng(w, h, ct, frames, plays=plays, plte=plte, trns=trns, rng=rng, split=split)
|
|
mine = composite(w, h, ct, frames, plte, trns)
|
|
ref = ffmpeg_frames(ctx, data, w, h)
|
|
if ct in (0, 2): # ffmpeg decodes to an opaque pixel format: disposed pixels come out opaque black
|
|
mine = [bytes(v if i % 4 != 3 else 255 for i, v in enumerate(m)) for m in mine]
|
|
if ref != mine:
|
|
for fi, (a, b) in enumerate(zip(ref, mine)):
|
|
if a != b:
|
|
k = next(j for j in range(len(a)) if a[j] != b[j])
|
|
print("apng fixture mismatch:", name, fi, k // 4 % w, k // 4 // w, a[k - k % 4:k - k % 4 + 4], b[k - k % 4:k - k % 4 + 4], frames[fi]["dispose"], frames[fi]["blend"], frames[fi - 1]["dispose"] if fi else None, sum(1 for j in range(0, len(a), 4) if a[j:j + 4] != b[j:j + 4]))
|
|
raise RuntimeError("apng fixture %s: ffmpeg and the reference compositor disagree (%d vs %d frames)" % (name, len(ref), len(mine)))
|
|
add(name, data, w, h, frames, ref, plays=plays, opaque=ct in (0, 2))
|
|
|
|
# every dispose x blend on sub-rectangles over a semi-transparent background
|
|
W, H = 20, 16
|
|
fr = [frame(rng, 6, 0, 0, W, H, 0, 0)]
|
|
for d in (0, 1, 2):
|
|
for b in (0, 1):
|
|
fr.append(frame(rng, 6, rng.randrange(8), rng.randrange(6), 1 + rng.randrange(12), 1 + rng.randrange(10), d, b, num=rng.randrange(1, 200), den=rng.choice((0, 100, 1000))))
|
|
fr.append(frame(rng, 6, 3, 2, 9, 7, 2, 1))
|
|
fr.append(frame(rng, 6, 0, 0, W, H, 0, 1))
|
|
hand("rgba-dispose-blend", W, H, 6, fr, plays=3, split=2)
|
|
# first frame dispose previous (= background), then over
|
|
hand("first-previous", 12, 9, 6, [frame(rng, 6, 0, 0, 12, 9, 2, 1), frame(rng, 6, 2, 2, 5, 4, 0, 1), frame(rng, 6, 0, 0, 3, 3, 1, 0)])
|
|
# palette + tRNS, over
|
|
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(40)]
|
|
trns = [rng.choice((0, 128, 255, rng.randrange(256))) for _ in range(30)]
|
|
hand("palette-trns", 17, 13, 3, [frame(rng, 3, 0, 0, 17, 13, 1, 0, ncolors=40)] + [frame(rng, 3, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(12), 1 + rng.randrange(8), rng.randrange(3), rng.randrange(2), ncolors=40) for _ in range(5)], plte=pal, trns=trns)
|
|
# grey and RGB (no alpha: over = source)
|
|
hand("gray", 15, 11, 0, [frame(rng, 0, 0, 0, 15, 11, 0, 0)] + [frame(rng, 0, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)], plays=1)
|
|
hand("rgb", 15, 11, 2, [frame(rng, 2, 0, 0, 15, 11, 1, 0)] + [frame(rng, 2, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)])
|
|
# a single-frame APNG
|
|
hand("one-frame", 7, 5, 6, [frame(rng, 6, 0, 0, 7, 5, 0, 0)])
|
|
|
|
# hidden default image (not part of the animation): ffmpeg's demuxer cannot express it, so the compositor here
|
|
dpx = sprite(rng, 10, 8, 6)
|
|
fr = [frame(rng, 6, 0, 0, 10, 8, 0, 0), frame(rng, 6, 2, 1, 4, 5, 1, 1), frame(rng, 6, 5, 3, 5, 5, 0, 1)]
|
|
data = apng(10, 8, 6, fr, default=dpx, rng=rng)
|
|
add("hidden-default", data, 10, 8, fr, composite(10, 8, 6, fr), default_crc=zlib.crc32(b"".join(bytes(p) for row in dpx for p in row)), ffmpeg=False)
|
|
|
|
# ffmpeg's own encoder (it picks sub-rectangles, dispose and blend ops)
|
|
for name, src, pix, plays in (
|
|
("ffmpeg-testsrc", "testsrc=size=40x30:rate=10", "rgb24", 0),
|
|
("ffmpeg-rgba", "testsrc2=size=36x28:rate=8,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(mod(X+T*40,20),10),255,90)'", "rgba", 2),
|
|
):
|
|
data = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-frames:v", "7", "-pix_fmt", pix, "-plays", str(plays), "-f", "apng", "-"],
|
|
capture_output=True, check=True).stdout
|
|
w, h = struct.unpack(">II", data[16:24])
|
|
ref = ffmpeg_frames(ctx, data, w, h)
|
|
cases.append({"name": name, "data": data, "width": w, "height": h, "plays": plays, "crcs": [zlib.crc32(r) for r in ref], "ffmpeg": True, "opaque": pix == "rgb24"})
|
|
|
|
ctx.emit("apng_cases", cases)
|