Files
rosetta/tools/fixtures/psd.py
T

390 lines
18 KiB
Python

# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32
# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden
# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference):
# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image),
# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } },
# flat (psd-tools' composite of the layers, RGBA) } } }
# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with
# luau) read by psd-tools, compared with the layers and the flattened image we wrote.
import json, os, random, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Rosetta/layered/psd", "src/Rosetta/codecs/image/Blend.luau", "src/Rosetta/ops/LayerOps.luau", "tools/fixtures/_ours.luau"]
BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit",
"hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "]
def packbits(row):
out, i, n = bytearray(), 0, len(row)
while i < n:
j = i
while j + 1 < n and row[j + 1] == row[i] and j - i < 127:
j += 1
if j - i >= 2:
out += bytes([257 - (j - i + 1), row[i]])
i = j + 1
else:
k = i
while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]):
k += 1
out += bytes([k - i - 1]) + row[i:k]
i = k
return bytes(out)
def bytes_per(depth):
return {8: 1, 16: 2, 32: 4}[depth]
def channel_data(plane, w, h, depth, comp, psb=False):
"""plane: bytes (rows of w samples, big endian) -> compression code + data"""
rb = w * bytes_per(depth)
if w == 0 or h == 0:
return struct.pack(">H", 0)
if comp == 0:
return struct.pack(">H", 0) + plane
if comp == 1:
rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)]
fmt = ">I" if psb else ">H"
return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
if comp == 2:
return struct.pack(">H", 2) + zlib.compress(plane)
# zip with prediction
out = bytearray()
for y in range(h):
row = plane[y * rb:(y + 1) * rb]
if depth == 8:
out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)])
elif depth == 16:
vals = struct.unpack(">%dH" % w, row)
out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)]))
else:
planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w))
out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))])
return struct.pack(">H", 3) + zlib.compress(bytes(out))
def pascal(name, pad=4):
b = name.encode("latin-1", "replace")[:255]
s = bytes([len(b)]) + b
while len(s) % pad:
s += b"\0"
return s
def block(key, data, psb=False):
while len(data) % 4:
data += b"\0"
return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data
def luni(name):
u = name.encode("utf-16-be")
return struct.pack(">I", len(u) // 2) + u
class Layer:
def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None,
section_blend=None, fill=None, mask=None, comp=1):
self.__dict__.update(locals())
def layer_info(layers, depth, psb, neg):
recs, data = bytearray(), bytearray()
for L in layers:
recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w)
chans = list(L.chans.items())
if L.mask:
chans.append((-2, L.mask["plane"]))
recs += struct.pack(">H", len(chans))
for cid, plane in chans:
if cid == -2:
m = L.mask
cd = channel_data(plane, m["w"], m["h"], depth, 1, psb)
else:
cd = channel_data(plane, L.w, L.h, depth, L.comp, psb)
recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd)))
data += cd
flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0)
recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0])
ex = bytearray()
if L.mask:
m = L.mask
ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0)
else:
ex += struct.pack(">I", 0)
ex += struct.pack(">I", 0)
ex += pascal(L.name)
ex += block(b"luni", luni(L.name))
if L.section is not None:
ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b""))
if L.fill is not None:
ex += block(b"iOpa", bytes([L.fill, 0, 0, 0]))
recs += struct.pack(">I", len(ex)) + ex
body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data
if len(body) % 2:
body += b"\0"
return body
def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""):
out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode)
cm = palette or b""
out += struct.pack(">I", len(cm)) + cm
out += struct.pack(">I", len(resources)) + resources
L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n)
if layers:
li = layer_info(layers, depth, psb, neg)
if lr16:
lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb)
else:
lm = L(len(li)) + li + struct.pack(">I", 0)
out += L(len(lm)) + lm
else:
out += L(0)
rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth)
if comp == 0:
out += struct.pack(">H", 0) + b"".join(merged_planes)
elif comp == 1:
rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)]
fmt = ">I" if psb else ">H"
out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
else:
out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes))
return out
def plane8(w, h, f):
return bytes(f(x, y) & 255 for y in range(h) for x in range(w))
def plane16(w, h, f):
return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w))
def plane32(w, h, f):
return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w))
def rgba_layer(name, left, top, w, h, seed, **kw):
rng = random.Random(seed)
k = [rng.randrange(1, 9) for _ in range(8)]
chans = {
0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]),
1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]),
2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5),
-1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160),
}
return Layer(name, left, top, w, h, chans, **kw)
def divider():
return Layer("</Layer group>", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3)
def group(name, blend="pass", opacity=255, hidden=False):
return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden)
def merged_rgb(w, h, alpha=True):
ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)]
if alpha:
ps.append(plane8(w, h, lambda x, y: 255 - x))
return ps
def cases():
W, H = 40, 30
out = []
# 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression
mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)}
layers = [
rgba_layer("Background", 0, 0, W, H, 1, comp=0),
rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200),
divider(),
rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2),
rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3),
group("Isolated", blend="norm", opacity=180),
divider(),
rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"),
rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True),
group("Pass"),
rgba_layer("Base", 20, 15, 15, 10, 7),
rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "),
rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask),
rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"),
]
out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers)))
# 2. every blend mode on its own (two layers)
for key in BLEND:
ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)]
out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls)))
# 3. 16-bit RGB with the layers in Lr16, ZIP with prediction
ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)}
l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")]
m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)]
out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True)))
# 4. 32-bit: merged only (floats) and a layer in Lr32
m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)]
l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)]
out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0)))
# 5. greyscale with layers, raw merged
gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}),
Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")]
out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0)))
# 6. CMYK, merged + a layer
cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)]
cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})]
out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl)))
# 7. indexed (merged only), 8. bitmap (merged only), 9. Lab
pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256))
out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1)))
out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0)))
out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1)))
# 10. PSB with layers (8-byte lengths, 4-byte RLE counts)
out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True)))
# 11. no alpha in the merged image, positive layer count
out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False)))
return out
REF = r'''
import json, os, sys, zlib
from psd_tools import PSDImage
d = %r
res = []
for name in sorted(os.listdir(d)):
if not name.endswith(".psd"):
continue
psd = PSDImage.open(os.path.join(d, name))
c = {"name": name[:-4], "width": psd.width, "height": psd.height}
try:
im = psd.topil()
c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else ""
except Exception as e:
c["composite"] = ""
layers = []
for l in psd.descendants():
if l.is_group():
layers.append({"name": l.name, "group": True})
continue
e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height}
try:
im = l.topil()
if im is not None:
e["crc"] = zlib.crc32(im.convert("RGBA").tobytes())
except Exception:
pass
layers.append(e)
c["layers"] = layers
try:
f = psd.composite(force=True, color=0.0, alpha=0.0)
c["flat"] = f.convert("RGBA").tobytes().hex()
except Exception as e:
c["flaterr"] = str(e)
res.append(c)
print(json.dumps(res))
'''
def pyrun(ctx, code):
try:
return ctx.python(["psd-tools", "numpy", "pillow"], code)
except subprocess.CalledProcessError as e:
raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace"))
def reference(ctx, files):
with tempfile.TemporaryDirectory() as d:
for name, data in files:
open(os.path.join(d, name + ".psd"), "wb").write(data)
res = json.loads(pyrun(ctx, REF % d))
by = {r["name"]: r for r in res}
out = []
for name, data in files:
r = by[name]
case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])}
if "flat" in r:
case["flat"] = bytes.fromhex(r["flat"])
case["layers"] = r["layers"]
out.append(case)
return out
def imagemagick(ctx):
# image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed
# ("mron"), which psd-tools refuses: these layers avoid it)
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "im.psd")
argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")",
"(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p]
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(p, "rb").read()
def generate(ctx):
files = cases()
files.append(("imagemagick", imagemagick(ctx)))
ctx.emit("psd", {"cases": reference(ctx, files)})
ctx.emit("psd_ours", {"checks": ours(ctx)})
def run_ours(ctx, fmt):
"""our encoder's output and facts, from tools/fixtures/_ours.luau"""
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
argv = [shutil.which("luau") or "luau", script, "-a", fmt]
if shutil.which("luau"):
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
else:
out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout
return json.loads(out)
OURS = r'''
import json, sys, zlib
from psd_tools import PSDImage
psd = PSDImage.open(%r)
res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []}
for l in psd.descendants():
if l.is_group():
res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible})
continue
res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height,
"crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity,
"visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()})
print(json.dumps(res))
'''
PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"}
def ours(ctx):
o = run_ours(ctx, "psd")
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "ours.psd")
open(p, "wb").write(bytes.fromhex(o["data"]))
ref = json.loads(pyrun(ctx, OURS % p))
checks = []
def check(label, ok):
checks.append({"label": label, "ok": bool(ok)})
check("psd-tools: composite = our flatten", ref["composite"] == o["composite"])
leaves = [l for l in ref["layers"] if not l.get("group")]
check("psd-tools: leaf count", len(leaves) == len(o["layers"]))
for want, got in zip(o["layers"], leaves):
n = want["name"]
check(n + ": name", got["name"] == n)
check(n + ": pixels", got["crc"] == want["crc"])
check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"]))
check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?")))
check(n + ": opacity", got["opacity"] == want["opacity"])
check(n + ": visible", got["visible"] == want["visible"])
check(n + ": clip", got["clip"] == want["clip"])
groups = [l for l in ref["layers"] if l.get("group")]
check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"])
check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL"))
check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked"))
return checks